From 4ddd33a12260e8c2dfdaa876b6d309ca07011c0c Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 12:03:04 +0100 Subject: [PATCH 1/7] fix(codecs): build sharded and v2 buffers from the given prototype The sharding codec refused any prototype other than the one `zarr.config` names, and built shard blobs, the shard index, and empty shard readers from `zarr.config`. The v2 codec built decoded chunks from `zarr.config` too. A read or write that passed a prototype different from the configured one therefore failed (sharded arrays) or decoded through the configured kind (v2 arrays). Codecs now use the prototype in the chunk spec. The shard index stays in host memory whatever the data prototype, because it is consumed as a NumPy array; it is converted to the shard's buffer kind when the shard is assembled. Buffers an inner codec returns in another kind are converted at the shard boundary, so codecs that ignore the prototype keep working. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- src/zarr/codecs/_v2.py | 3 +- src/zarr/codecs/sharding.py | 81 +++-- tests/test_codecs/test_buffer_prototype.py | 337 +++++++++++++++++++++ tests/test_codecs/test_sharding_unit.py | 8 +- 4 files changed, 401 insertions(+), 28 deletions(-) create mode 100644 tests/test_codecs/test_buffer_prototype.py diff --git a/src/zarr/codecs/_v2.py b/src/zarr/codecs/_v2.py index 7c33caaa61..52fef97797 100644 --- a/src/zarr/codecs/_v2.py +++ b/src/zarr/codecs/_v2.py @@ -10,7 +10,6 @@ from zarr.abc.codec import ArrayBytesCodec from zarr.core.config import config from zarr.errors import PickleCodecDisabledError -from zarr.registry import get_ndbuffer_class if TYPE_CHECKING: from zarr.abc.numcodec import Numcodec @@ -94,7 +93,7 @@ def _decode_sync( chunk = chunk.reshape(-1, order="A") chunk = chunk.reshape(chunk_spec.shape, order=chunk_spec.order) - return get_ndbuffer_class().from_ndarray_like(chunk) + return chunk_spec.prototype.nd_buffer.from_ndarray_like(chunk) def _encode_sync( self, diff --git a/src/zarr/codecs/sharding.py b/src/zarr/codecs/sharding.py index d4ccf71cb9..6e3d2c3dec 100644 --- a/src/zarr/codecs/sharding.py +++ b/src/zarr/codecs/sharding.py @@ -33,7 +33,6 @@ Buffer, BufferPrototype, NDBuffer, - default_buffer_prototype, numpy_buffer_prototype, ) from zarr.core.chunk_grids import ChunkGrid @@ -73,7 +72,7 @@ RegularChunkGridMetadata, parse_codecs, ) -from zarr.registry import get_ndbuffer_class, get_pipeline_class +from zarr.registry import get_pipeline_class from zarr.storage._common import StorePath from zarr.storage._utils import _normalize_byte_range_index @@ -145,6 +144,33 @@ def _parse_index_location(data: object) -> IndexLocation: raise ValueError(f"index_location must be one of {list(INDEX_LOCATION)!r}. Got {data!r}.") +def _as_prototype_buffer(buffer: Buffer, prototype: BufferPrototype) -> Buffer: + """Return `buffer` as an instance of `prototype.buffer`, converting only on a mismatch. + + The bytes inside a shard come from the shard read (made with the call's + prototype) or from the inner codecs (asked to use it). A codec that ignores + `chunk_spec.prototype` and builds its buffers some other way, for instance + from `zarr.config`, can still hand back a buffer of another kind; converting + here keeps that buffer from reaching the caller or the shard blob. + """ + if isinstance(buffer, prototype.buffer): + return buffer + return prototype.buffer.from_buffer(buffer) + + +def _host_buffer(buffer: Buffer) -> Buffer: + """Return `buffer` in host memory as a `zarr.core.buffer.cpu.Buffer`. + + The shard index is decoded into a NumPy array (`_ShardIndex` holds one), so + its bytes are moved to the host before the index codecs see them, whatever + prototype the shard itself was read with. + """ + host_buffer = numpy_buffer_prototype().buffer + if isinstance(buffer, host_buffer): + return buffer + return host_buffer.from_buffer(buffer) + + @dataclass(frozen=True) class _ShardingByteGetter(ByteGetter): """In-memory byte getter for one inner chunk of a shard. @@ -161,18 +187,15 @@ class _ShardingByteGetter(ByteGetter): def get_sync( self, prototype: BufferPrototype | None = None, byte_range: ByteRequest | None = None ) -> Buffer | None: - if prototype is not None and prototype != default_buffer_prototype(): - raise ValueError( - "Non-default buffer prototypes are not supported within shards. " - f"Got {prototype}, expected {default_buffer_prototype()}." - ) value = self.shard_dict.get(self.chunk_coords) if value is None: return None - if byte_range is None: + if byte_range is not None: + start, stop = _normalize_byte_range_index(value, byte_range) + value = value[start:stop] + if prototype is None: return value - start, stop = _normalize_byte_range_index(value, byte_range) - return value[start:stop] + return _as_prototype_buffer(value, prototype) async def get( self, prototype: BufferPrototype, byte_range: ByteRequest | None = None @@ -344,10 +367,8 @@ async def from_bytes( @classmethod def create_empty( - cls, chunks_per_shard: tuple[int, ...], buffer_prototype: BufferPrototype | None = None + cls, chunks_per_shard: tuple[int, ...], buffer_prototype: BufferPrototype ) -> _ShardReader: - if buffer_prototype is None: - buffer_prototype = default_buffer_prototype() index = _ShardIndex.create_empty(chunks_per_shard) obj = cls() obj.buf = buffer_prototype.buffer.create_zero_length() @@ -655,7 +676,9 @@ def _validate_inner_codecs(self, dtype: ZDType[TBaseDType, TBaseScalar]) -> None dtype=dtype, fill_value=dtype.default_scalar(), config=ArrayConfig.from_dict({}), - prototype=default_buffer_prototype(), + # Validation builds no buffers, so any prototype will do; a fixed one + # keeps validation from reading `zarr.config`. + prototype=numpy_buffer_prototype(), ) for codec in self.codecs: codec.validate( @@ -697,6 +720,7 @@ def _decode_shard_index_sync( ) -> _ShardIndex: """Decode shard index synchronously using ChunkTransform.""" self._check_shard_index_size(index_bytes, chunks_per_shard) + index_bytes = _host_buffer(index_bytes) index_transform = self._get_index_chunk_transform(chunks_per_shard) index_spec = self._get_index_chunk_spec(chunks_per_shard) index_array = index_transform.decode_chunk(index_bytes, index_spec) @@ -706,7 +730,7 @@ def _encode_shard_index_sync(self, index: _ShardIndex) -> Buffer: """Encode shard index synchronously using ChunkTransform.""" index_transform = self._get_index_chunk_transform(index.chunks_per_shard) index_spec = self._get_index_chunk_spec(index.chunks_per_shard) - index_nd = get_ndbuffer_class().from_numpy_array(index.offsets_and_lengths) + index_nd = index_spec.prototype.nd_buffer.from_numpy_array(index.offsets_and_lengths) result: Buffer | None = index_transform.encode_chunk(index_nd, index_spec) if result is None: raise RuntimeError("Encoding the shard index produced no bytes.") @@ -841,7 +865,7 @@ def _encode_sync( return self._encode_shard_dict_sync( shard_builder, chunks_per_shard=chunks_per_shard, - buffer_prototype=default_buffer_prototype(), + buffer_prototype=shard_spec.prototype, ) def _encode_partial_sync( @@ -943,7 +967,7 @@ def _encode_partial_sync( blob = self._encode_shard_dict_sync( shard_dict, chunks_per_shard=chunks_per_shard, - buffer_prototype=default_buffer_prototype(), + buffer_prototype=shard_spec.prototype, ) if blob is None: byte_setter.delete_sync() @@ -1008,6 +1032,12 @@ def _assemble_shard( "encoded shard index size does not match _shard_index_size; " "variable-size index codecs are not supported" ) + # The index is encoded in host memory (see `_get_index_chunk_spec`). Copy it + # through bytes rather than `from_buffer`: it is a few bytes per chunk, + # and a host-to-device `from_buffer` warns about taking the slow path. + if not isinstance(index_bytes, buffer_prototype.buffer): + index_bytes = buffer_prototype.buffer.from_bytes(index_bytes.to_bytes()) + buffers = [_as_prototype_buffer(buffer, buffer_prototype) for buffer in buffers] if self.index_location == "start": buffers.insert(0, index_bytes) else: @@ -1410,7 +1440,7 @@ async def _encode_single( return await self._encode_shard_dict( shard_builder, chunks_per_shard=chunks_per_shard, - buffer_prototype=default_buffer_prototype(), + buffer_prototype=shard_spec.prototype, ) async def _encode_partial_single( @@ -1434,7 +1464,7 @@ async def _encode_partial_single( chunks_per_shard=chunks_per_shard, ) if shard_reader is None: - shard_reader = _ShardReader.create_empty(chunks_per_shard) + shard_reader = _ShardReader.create_empty(chunks_per_shard, chunk_spec.prototype) # Use vectorized lookup for better performance. The lexicographic # coordinate array and keys are cached, so neither is rebuilt on # every write. @@ -1456,7 +1486,7 @@ async def _encode_partial_single( buf = await self._encode_shard_dict( shard_dict, chunks_per_shard=chunks_per_shard, - buffer_prototype=default_buffer_prototype(), + buffer_prototype=shard_spec.prototype, ) if buf is None: @@ -1579,6 +1609,7 @@ async def _decode_shard_index( if self._index_codecs_sync_capable(): return self._decode_shard_index_sync(index_bytes, chunks_per_shard) self._check_shard_index_size(index_bytes, chunks_per_shard) + index_bytes = _host_buffer(index_bytes) index_array = next( iter( await get_pipeline_class() @@ -1602,7 +1633,9 @@ async def _encode_shard_index(self, index: _ShardIndex) -> Buffer: .encode( [ ( - get_ndbuffer_class().from_numpy_array(index.offsets_and_lengths), + numpy_buffer_prototype().nd_buffer.from_numpy_array( + index.offsets_and_lengths + ), self._get_index_chunk_spec(index.chunks_per_shard), ) ] @@ -1647,7 +1680,11 @@ def _get_index_chunk_spec(self, chunks_per_shard: tuple[int, ...]) -> ArraySpec: config=ArrayConfig( order="C", write_empty_chunks=False ), # Note: this is hard-coded for simplicity -- it is not surfaced into user code, - prototype=default_buffer_prototype(), + # The index lives in host memory whatever prototype the shard data uses: + # it is a few bytes per chunk, and it is consumed as a NumPy array + # (`_ShardIndex.offsets_and_lengths`). `_assemble_shard` converts the + # encoded index to the shard's prototype when writing. + prototype=numpy_buffer_prototype(), ) def _get_chunk_spec(self, shard_spec: ArraySpec) -> ArraySpec: diff --git a/tests/test_codecs/test_buffer_prototype.py b/tests/test_codecs/test_buffer_prototype.py new file mode 100644 index 0000000000..2876ee0c98 --- /dev/null +++ b/tests/test_codecs/test_buffer_prototype.py @@ -0,0 +1,337 @@ +"""Codecs build their buffers from the prototype they are given, not from `zarr.config`. + +A read or write takes a `BufferPrototype`; `zarr.config` names another +(`buffer` / `ndbuffer`). These tests set the two to different buffer kinds and +check that only the given prototype's kind appears: in the array a read +returns, in the values the store receives, and in the arrays each codec sees. + +The test buffer kind (`TestBuffer` / `NDBufferUsingTestNDArrayLike`) subclasses +the CPU kind, so the tests compare exact types: a value of the configured kind +leaking out would otherwise pass an `isinstance` check. +""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Literal + +import numcodecs +import numpy as np +import pytest + +import zarr +from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec +from zarr.codecs import ( + BytesCodec, + Crc32cCodec, + GzipCodec, + ShardingCodec, + TransposeCodec, +) +from zarr.codecs import numcodecs as zarr_numcodecs +from zarr.codecs._v2 import V2Codec +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import Buffer, BufferPrototype, NDBuffer, cpu, default_buffer_prototype +from zarr.core.config import config +from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.registry import fully_qualified_name, register_buffer, register_ndbuffer +from zarr.storage import MemoryStore +from zarr.testing.buffer import NDBufferUsingTestNDArrayLike, TestBuffer, TestNDArrayLike + +if TYPE_CHECKING: + from zarr.abc.codec import Codec + +TEST_PROTOTYPE = BufferPrototype(buffer=TestBuffer, nd_buffer=NDBufferUsingTestNDArrayLike) +TEST_CONFIG = { + "buffer": fully_qualified_name(TestBuffer), + "ndbuffer": fully_qualified_name(NDBufferUsingTestNDArrayLike), +} +PIPELINES = ( + "zarr.core.codec_pipeline.BatchedCodecPipeline", + "zarr.core.codec_pipeline.FusedCodecPipeline", +) + + +@dataclass(frozen=True) +class Direction: + """A prototype to call with, and a `zarr.config` naming a different buffer kind.""" + + name: str + prototype: BufferPrototype + buffer_config: dict[str, str] + array_type: type[np.ndarray[Any, Any]] + + +DIRECTIONS = ( + # The configured kind is the test kind; the call asks for the CPU kind. + Direction("config-test-call-cpu", cpu.buffer_prototype, TEST_CONFIG, np.ndarray), + # The configured kind is the default CPU kind; the call asks for the test kind. + Direction("config-cpu-call-test", TEST_PROTOTYPE, {}, TestNDArrayLike), +) + + +@pytest.fixture(autouse=True) +def _register_test_buffers() -> None: + register_buffer(TestBuffer) + register_ndbuffer(NDBufferUsingTestNDArrayLike) + + +class RecordingStore(MemoryStore): + """A `MemoryStore` that records the type of every chunk value written to it.""" + + def __init__(self) -> None: + super().__init__() + self.chunk_value_types: set[type[Buffer]] = set() + + def _record(self, key: str, value: Buffer) -> None: + if not key.endswith((".json", ".zarray", ".zattrs", ".zgroup")): + self.chunk_value_types.add(type(value)) + + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: + self._record(key, value) + await super().set(key, value, byte_range) + + def set_sync(self, key: str, value: Buffer) -> None: + self._record(key, value) + super().set_sync(key, value) + + +@dataclass(frozen=True) +class ExpectPrototypeCodec(ArrayArrayCodec): + """A no-op codec that fails unless its input has the exact type the spec's prototype names. + + Placed first in a codec chain, it sees the array the pipeline hands to the + codecs on encode, and the array the rest of the chain decodes on decode. + """ + + is_fixed_size = True + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-expect-prototype"} + + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: + return input_byte_length + + def _check(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + assert type(chunk_array) is chunk_spec.prototype.nd_buffer, ( + f"expected {chunk_spec.prototype.nd_buffer}, got {type(chunk_array)}" + ) + return chunk_array + + _encode_sync = _check + _decode_sync = _check + + async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._check(chunk_array, chunk_spec) + + async def _decode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._check(chunk_array, chunk_spec) + + +@dataclass(frozen=True) +class AsyncOnlyCodec(BytesBytesCodec): + """A no-op codec with only the async interface, like codecs written before the sync one.""" + + is_fixed_size = True + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-async-only"} + + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: + return input_byte_length + + async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return chunk_bytes + + async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return chunk_bytes + + +@dataclass(frozen=True) +class ConfigBufferCodec(BytesBytesCodec): + """A no-op codec that ignores `chunk_spec.prototype` and builds its output from `zarr.config`. + + Stands for a codec written outside zarr that predates prototypes. It records + that it ran, so a test can tell it was not skipped. + """ + + is_fixed_size = True + calls: list[str] = field(default_factory=list, compare=False, hash=False) + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-config-buffer"} + + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: + return input_byte_length + + def _convert(self, chunk_bytes: Buffer, direction: str) -> Buffer: + self.calls.append(direction) + return default_buffer_prototype().buffer.from_bytes(chunk_bytes.to_bytes()) + + def _encode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return self._convert(chunk_bytes, "encode") + + def _decode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return self._convert(chunk_bytes, "decode") + + async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return self._encode_sync(chunk_bytes, chunk_spec) + + async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return self._decode_sync(chunk_bytes, chunk_spec) + + +def _zarr_chain() -> list[Codec]: + return [ExpectPrototypeCodec(), TransposeCodec(order=(1, 0)), BytesCodec(), GzipCodec()] + + +def _numcodecs_chain() -> list[Codec]: + return [ + ExpectPrototypeCodec(), + zarr_numcodecs.Delta(dtype=" list[Codec]: + return [ExpectPrototypeCodec(), BytesCodec(), AsyncOnlyCodec(), Crc32cCodec()] + + +CHAINS = {"zarr": _zarr_chain, "numcodecs": _numcodecs_chain, "async-only": _async_only_chain} +Layout = Literal["v3", "v3-sharded", "v3-nested-sharded", "v2"] + + +def _chain_kwargs(chain: list[Codec]) -> dict[str, Any]: + """Split a v3 codec chain into `create_array`'s filters, serializer and compressors.""" + return { + "filters": [c for c in chain if isinstance(c, ArrayArrayCodec)], + "serializer": next(c for c in chain if isinstance(c, ArrayBytesCodec)), + "compressors": [c for c in chain if isinstance(c, BytesBytesCodec)], + } + + +def _create(store: MemoryStore, layout: Layout, chain: list[Codec]) -> zarr.Array[Any]: + """An (8, 8) int32 array of the given layout, with 2x2 chunks inside 4x4 shards.""" + common: dict[str, Any] = {"shape": (8, 8), "dtype": "int32", "fill_value": 0} + if layout == "v2": + return zarr.create_array( + store, + zarr_format=2, + chunks=(2, 2), + filters=[numcodecs.Delta(dtype=" list[tuple[Any, np.ndarray[Any, Any]]]: + """Write all of `array`, then part of it, then read all and part of it back. + + Returns each read result with its expected value. The partial write and read + each cross inner-chunk and shard boundaries. + """ + async_array = array._async_array + expected = np.arange(64, dtype="int32").reshape(8, 8) + await async_array.setitem((slice(None), slice(None)), expected, prototype=prototype) + await async_array.setitem( + (slice(1, 5), slice(3, 6)), np.full((4, 3), -7, dtype="int32"), prototype=prototype + ) + expected[1:5, 3:6] = -7 + full = await async_array.getitem((slice(None), slice(None)), prototype=prototype) + part = await async_array.getitem((slice(1, 6), slice(2, 7)), prototype=prototype) + return [(full, expected), (part, expected[1:6, 2:7])] + + +# A v2 array takes numcodecs filters and compressors, not a codec chain (see `_create`). +LAYOUT_CHAINS = [ + *((layout, chain) for layout in ("v3", "v3-sharded", "v3-nested-sharded") for chain in CHAINS), + ("v2", "numcodecs"), +] + + +@pytest.mark.parametrize("pipeline", PIPELINES) +@pytest.mark.parametrize("direction", DIRECTIONS, ids=lambda d: d.name) +@pytest.mark.parametrize(("layout", "chain"), LAYOUT_CHAINS) +def test_codecs_use_the_given_prototype( + pipeline: str, direction: Direction, layout: Layout, chain: str +) -> None: + """Reads and writes produce the given prototype's buffer kind, whatever `zarr.config` names. + + The `numcodecs` chain uses zarr's numcodecs wrappers and the `async-only` + chain a codec with no sync interface, both of the shape codecs from other + packages take. v2 arrays always use numcodecs filters and compressors. + """ + store = RecordingStore() + with config.set({**direction.buffer_config, "codec_pipeline.path": pipeline}): + array = _create(store, layout, CHAINS[chain]()) + results = asyncio.run(_round_trip(array, direction.prototype)) + for got, expected in results: + assert type(got) is direction.array_type + np.testing.assert_array_equal(got, expected) + assert store.chunk_value_types == {direction.prototype.buffer} + + +@pytest.mark.parametrize("pipeline", PIPELINES) +@pytest.mark.parametrize("direction", DIRECTIONS, ids=lambda d: d.name) +def test_sharding_converts_buffers_from_codecs_that_ignore_the_prototype( + pipeline: str, direction: Direction +) -> None: + """A shard gets the given prototype's buffer kind even when an inner codec ignores it. + + `ConfigBufferCodec` returns buffers of the configured kind. The sharding codec + converts them before they reach the shard it writes or the reads it serves. + """ + codec = ConfigBufferCodec() + store = RecordingStore() + with config.set({**direction.buffer_config, "codec_pipeline.path": pipeline}): + array = _create(store, "v3-sharded", [BytesCodec(), codec]) + results = asyncio.run(_round_trip(array, direction.prototype)) + for got, expected in results: + assert type(got) is direction.array_type + np.testing.assert_array_equal(got, expected) + assert store.chunk_value_types == {direction.prototype.buffer} + assert {"encode", "decode"} <= set(codec.calls) + + +@pytest.mark.parametrize("direction", DIRECTIONS, ids=lambda d: d.name) +def test_v2_codec_decodes_into_the_given_prototype(direction: Direction) -> None: + """`V2Codec` returns the spec's prototype's array kind, not the configured one. + + The pipeline copies a decoded chunk into an output buffer of the call's kind, + so an array read alone would not show a decoded chunk of the wrong kind. + """ + zdtype = get_data_type_from_native_dtype(np.dtype("int32")) + spec = ArraySpec( + shape=(2, 2), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig.from_dict({}), + prototype=direction.prototype, + ) + codec = V2Codec(filters=(numcodecs.Delta(dtype=" None: """Test _ShardReader.create_empty creates reader with empty index.""" chunks_per_shard = (2, 3) - reader = _ShardReader.create_empty(chunks_per_shard) + reader = _ShardReader.create_empty(chunks_per_shard, buffer_prototype) assert reader.index.is_all_empty() assert len(reader.buf) == 0 @@ -468,7 +468,7 @@ def test_shard_reader_create_empty() -> None: def test_shard_reader_iteration() -> None: """Test _ShardReader iteration yields all chunk coordinates.""" chunks_per_shard = (2, 2) - reader = _ShardReader.create_empty(chunks_per_shard) + reader = _ShardReader.create_empty(chunks_per_shard, buffer_prototype) coords = list(reader) @@ -482,7 +482,7 @@ def test_shard_reader_iteration() -> None: def test_shard_reader_getitem_raises_for_empty() -> None: """Test _ShardReader.__getitem__ raises KeyError for empty chunks.""" chunks_per_shard = (2,) - reader = _ShardReader.create_empty(chunks_per_shard) + reader = _ShardReader.create_empty(chunks_per_shard, buffer_prototype) with pytest.raises(KeyError): _ = reader[(0,)] From a045f43f471763a5a268bbe8548e044b66ddeced Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 12:24:20 +0100 Subject: [PATCH 2/7] fix(codecs): convert each codec's buffers to the chunk's prototype in the pipelines A codec that ignores `chunk_spec.prototype` (for instance one that builds its buffers from `zarr.config`, as codecs from other packages may) could hand a buffer of another kind (host or device memory) to the next codec, the store, or the output array. Converting only at the shard boundary missed inner decode stages, the shard index codecs, and unsharded arrays. `ChunkTransform`, `AsyncChunkTransform` and `BatchedCodecPipeline` now pass every codec's input and output through `_as_prototype_buffer` / `_as_prototype_nd_buffer`, which convert only on a type mismatch, and `scatter_chunk` converts partial-decode output the same way. The sharding codec's own conversions, now redundant, are removed; it keeps the host-memory index spec and converts the encoded index to the shard's kind with `from_bytes`, which on a GPU avoids the slow-path copy `combine` would take. The tests now use a fake device buffer kind that, like CuPy, refuses to mix with host memory, add chains whose last codec ignores the prototype, a bytes-only shard index, a `zarr.config` naming a buffer kind that cannot be built, and direct tests of the chain runners and `scatter_chunk`. Each of 18 single-site reversions of the change fails at least one test. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- src/zarr/codecs/sharding.py | 47 +- src/zarr/core/buffer/core.py | 26 + src/zarr/core/chunk_utils.py | 28 +- src/zarr/core/codec_pipeline.py | 119 +++-- tests/test_codecs/test_buffer_prototype.py | 562 ++++++++++++++++----- 5 files changed, 580 insertions(+), 202 deletions(-) diff --git a/src/zarr/codecs/sharding.py b/src/zarr/codecs/sharding.py index 6e3d2c3dec..0838857dee 100644 --- a/src/zarr/codecs/sharding.py +++ b/src/zarr/codecs/sharding.py @@ -144,33 +144,6 @@ def _parse_index_location(data: object) -> IndexLocation: raise ValueError(f"index_location must be one of {list(INDEX_LOCATION)!r}. Got {data!r}.") -def _as_prototype_buffer(buffer: Buffer, prototype: BufferPrototype) -> Buffer: - """Return `buffer` as an instance of `prototype.buffer`, converting only on a mismatch. - - The bytes inside a shard come from the shard read (made with the call's - prototype) or from the inner codecs (asked to use it). A codec that ignores - `chunk_spec.prototype` and builds its buffers some other way, for instance - from `zarr.config`, can still hand back a buffer of another kind; converting - here keeps that buffer from reaching the caller or the shard blob. - """ - if isinstance(buffer, prototype.buffer): - return buffer - return prototype.buffer.from_buffer(buffer) - - -def _host_buffer(buffer: Buffer) -> Buffer: - """Return `buffer` in host memory as a `zarr.core.buffer.cpu.Buffer`. - - The shard index is decoded into a NumPy array (`_ShardIndex` holds one), so - its bytes are moved to the host before the index codecs see them, whatever - prototype the shard itself was read with. - """ - host_buffer = numpy_buffer_prototype().buffer - if isinstance(buffer, host_buffer): - return buffer - return host_buffer.from_buffer(buffer) - - @dataclass(frozen=True) class _ShardingByteGetter(ByteGetter): """In-memory byte getter for one inner chunk of a shard. @@ -179,6 +152,10 @@ class _ShardingByteGetter(ByteGetter): synchronous codec pipeline takes its sync fast path on inner chunks instead of scheduling one coroutine per chunk; the async `get` simply delegates to `get_sync`. + + `prototype` is not used: the buffers are slices of the shard, in the buffer + kind it was read or encoded with, and the codec chains convert their input + to the kind their chunk spec names (see `_as_prototype_buffer`). """ shard_dict: ShardMapping @@ -190,12 +167,10 @@ def get_sync( value = self.shard_dict.get(self.chunk_coords) if value is None: return None - if byte_range is not None: - start, stop = _normalize_byte_range_index(value, byte_range) - value = value[start:stop] - if prototype is None: + if byte_range is None: return value - return _as_prototype_buffer(value, prototype) + start, stop = _normalize_byte_range_index(value, byte_range) + return value[start:stop] async def get( self, prototype: BufferPrototype, byte_range: ByteRequest | None = None @@ -720,7 +695,6 @@ def _decode_shard_index_sync( ) -> _ShardIndex: """Decode shard index synchronously using ChunkTransform.""" self._check_shard_index_size(index_bytes, chunks_per_shard) - index_bytes = _host_buffer(index_bytes) index_transform = self._get_index_chunk_transform(chunks_per_shard) index_spec = self._get_index_chunk_spec(chunks_per_shard) index_array = index_transform.decode_chunk(index_bytes, index_spec) @@ -1037,7 +1011,6 @@ def _assemble_shard( # and a host-to-device `from_buffer` warns about taking the slow path. if not isinstance(index_bytes, buffer_prototype.buffer): index_bytes = buffer_prototype.buffer.from_bytes(index_bytes.to_bytes()) - buffers = [_as_prototype_buffer(buffer, buffer_prototype) for buffer in buffers] if self.index_location == "start": buffers.insert(0, index_bytes) else: @@ -1609,7 +1582,6 @@ async def _decode_shard_index( if self._index_codecs_sync_capable(): return self._decode_shard_index_sync(index_bytes, chunks_per_shard) self._check_shard_index_size(index_bytes, chunks_per_shard) - index_bytes = _host_buffer(index_bytes) index_array = next( iter( await get_pipeline_class() @@ -1682,8 +1654,9 @@ def _get_index_chunk_spec(self, chunks_per_shard: tuple[int, ...]) -> ArraySpec: ), # Note: this is hard-coded for simplicity -- it is not surfaced into user code, # The index lives in host memory whatever prototype the shard data uses: # it is a few bytes per chunk, and it is consumed as a NumPy array - # (`_ShardIndex.offsets_and_lengths`). `_assemble_shard` converts the - # encoded index to the shard's prototype when writing. + # (`_ShardIndex.offsets_and_lengths`). The index codec chain moves index + # bytes read with the shard's prototype to the host, and + # `_assemble_shard` converts the encoded index to the shard's prototype. prototype=numpy_buffer_prototype(), ) diff --git a/src/zarr/core/buffer/core.py b/src/zarr/core/buffer/core.py index d2cd4a795b..6952edb0b5 100644 --- a/src/zarr/core/buffer/core.py +++ b/src/zarr/core/buffer/core.py @@ -598,6 +598,32 @@ class BufferPrototype(NamedTuple): nd_buffer: type[NDBuffer] +def _as_prototype_buffer(buffer: Buffer, prototype: BufferPrototype) -> Buffer: + """Return `buffer` as an instance of `prototype.buffer`, converting only on a mismatch. + + The codec pipelines pass every codec's input and output through this (and + `_as_prototype_nd_buffer`), so a codec that builds its buffers some other + way than from `chunk_spec.prototype`, for instance from `zarr.config`, + cannot hand a buffer of another kind (host or device memory) to the next + codec, the store, or the caller. + """ + if isinstance(buffer, prototype.buffer): + return buffer + return prototype.buffer.from_buffer(buffer) + + +def _as_prototype_nd_buffer(nd_buffer: NDBuffer, prototype: BufferPrototype) -> NDBuffer: + """Return `nd_buffer` as an instance of `prototype.nd_buffer`, converting only on a mismatch. + + `NDBuffer` has no `from_buffer`; the conversion goes through a NumPy array + in host memory. It only runs for a codec that ignores `chunk_spec.prototype`. + See `_as_prototype_buffer`. + """ + if isinstance(nd_buffer, prototype.nd_buffer): + return nd_buffer + return prototype.nd_buffer.from_numpy_array(nd_buffer.as_numpy_array()) + + # The default buffer prototype used throughout the Zarr codebase. def default_buffer_prototype() -> BufferPrototype: from zarr.registry import ( diff --git a/src/zarr/core/chunk_utils.py b/src/zarr/core/chunk_utils.py index b26d5478b2..3cf4c9aab0 100644 --- a/src/zarr/core/chunk_utils.py +++ b/src/zarr/core/chunk_utils.py @@ -4,6 +4,7 @@ from typing import TYPE_CHECKING, Any, cast from zarr.abc.codec import GetResult, SupportsSyncCodec, _codec_supports_sync +from zarr.core.buffer.core import _as_prototype_buffer, _as_prototype_nd_buffer from zarr.core.indexing import is_scalar if TYPE_CHECKING: @@ -106,6 +107,9 @@ def scatter_chunk( if selected is None: out[out_selection] = fill_value_or_default(chunk_spec) return GetResult(status="missing") + # A partial decode (`decode_partial`) returns the array-bytes codec's output + # directly, so convert it here like the chain runners convert each stage. + selected = _as_prototype_nd_buffer(selected, chunk_spec.prototype) if drop_axes: selected = selected.squeeze(axis=drop_axes) out[out_selection] = selected @@ -225,6 +229,10 @@ class ChunkTransform: All codecs must implement `SupportsSyncCodec`. Construction will raise `TypeError` if any codec does not. + + Every codec gets its input, and every codec's output is passed on, as the + buffer kind `chunk_spec.prototype` names (see `_as_prototype_buffer`), so a + codec that ignores the prototype cannot mix buffer kinds in the chain. """ codecs: tuple[Codec, ...] @@ -315,15 +323,18 @@ def decode_chunk(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: configuration for this chunk. """ aa_specs, ab_spec = self._resolve_specs(chunk_spec) + prototype = chunk_spec.prototype - data: Buffer = chunk_bytes + data = _as_prototype_buffer(chunk_bytes, prototype) for bb_codec in reversed(self._bb_codecs): - data = bb_codec._decode_sync(data, ab_spec) + data = _as_prototype_buffer(bb_codec._decode_sync(data, ab_spec), prototype) - chunk_array: NDBuffer = self._ab_codec._decode_sync(data, ab_spec) + chunk_array = _as_prototype_nd_buffer(self._ab_codec._decode_sync(data, ab_spec), prototype) for aa_codec, aa_spec in zip(reversed(self._aa_codecs), reversed(aa_specs), strict=True): - chunk_array = aa_codec._decode_sync(chunk_array, aa_spec) + chunk_array = _as_prototype_nd_buffer( + aa_codec._decode_sync(chunk_array, aa_spec), prototype + ) return chunk_array @@ -341,24 +352,25 @@ def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | configuration for this chunk. """ aa_specs, ab_spec = self._resolve_specs(chunk_spec) + prototype = chunk_spec.prototype - aa_data: NDBuffer = chunk_array + aa_data = _as_prototype_nd_buffer(chunk_array, prototype) for aa_codec, aa_spec in zip(self._aa_codecs, aa_specs, strict=True): aa_result = aa_codec._encode_sync(aa_data, aa_spec) if aa_result is None: return None - aa_data = aa_result + aa_data = _as_prototype_nd_buffer(aa_result, prototype) ab_result = self._ab_codec._encode_sync(aa_data, ab_spec) if ab_result is None: return None - bb_data: Buffer = ab_result + bb_data = _as_prototype_buffer(ab_result, prototype) for bb_codec in self._bb_codecs: bb_result = bb_codec._encode_sync(bb_data, ab_spec) if bb_result is None: return None - bb_data = bb_result + bb_data = _as_prototype_buffer(bb_result, prototype) return bb_data diff --git a/src/zarr/core/codec_pipeline.py b/src/zarr/core/codec_pipeline.py index dd893ea8d8..dd27096be7 100644 --- a/src/zarr/core/codec_pipeline.py +++ b/src/zarr/core/codec_pipeline.py @@ -19,13 +19,13 @@ CodecPipeline, GetResult, ) +from zarr.core.buffer.core import _as_prototype_buffer, _as_prototype_nd_buffer from zarr.core.chunk_utils import ( ChunkTransform, _merge_chunk_array, chunk_is_empty, decode_and_scatter_chunk, evolve_codecs, - fill_value_or_default, merge_and_encode_chunk, scatter_chunk, ) @@ -128,6 +128,26 @@ def _unzip2[T, U](iterable: Iterable[tuple[T, U]]) -> tuple[list[T], list[U]]: return (out0, out1) +def _as_prototype_buffers( + chunks: Iterable[Buffer | None], prototypes: list[BufferPrototype] +) -> list[Buffer | None]: + """`_as_prototype_buffer` over a batch of chunks; a missing chunk stays `None`.""" + return [ + None if chunk is None else _as_prototype_buffer(chunk, prototype) + for chunk, prototype in zip(chunks, prototypes, strict=True) + ] + + +def _as_prototype_nd_buffers( + chunks: Iterable[NDBuffer | None], prototypes: list[BufferPrototype] +) -> list[NDBuffer | None]: + """`_as_prototype_nd_buffer` over a batch of chunks; a missing chunk stays `None`.""" + return [ + None if chunk is None else _as_prototype_nd_buffer(chunk, prototype) + for chunk, prototype in zip(chunks, prototypes, strict=True) + ] + + def resolve_batched(codec: Codec, chunk_specs: Iterable[ArraySpec]) -> Iterable[ArraySpec]: return [codec.resolve_metadata(chunk_spec) for chunk_spec in chunk_specs] @@ -521,7 +541,8 @@ class AsyncChunkTransform: correctly-evolved per-stage spec (via the shared `resolve_aa_specs`). Unlike ChunkTransform it places no `SupportsSyncCodec` requirement on the - codecs, so it works for async-only codecs. Unlike the batched codec API it + codecs, so it works for async-only codecs. Like ChunkTransform it passes + every codec's input and output as the kind `chunk_spec.prototype` names. Unlike the batched codec API it operates on one chunk at a time — the mini-batch fan-out is a BatchedCodecPipeline concern and deliberately not reintroduced here. """ @@ -545,15 +566,20 @@ def __post_init__(self) -> None: async def decode_chunk(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: """Decode one chunk through the chain (bb -> ab -> aa), async.""" aa_specs, ab_spec = resolve_aa_specs(self._aa_codecs, chunk_spec) + prototype = chunk_spec.prototype - data: Buffer = chunk_bytes + data = _as_prototype_buffer(chunk_bytes, prototype) for bb_codec in reversed(self._bb_codecs): - data = await bb_codec._decode_single(data, ab_spec) + data = _as_prototype_buffer(await bb_codec._decode_single(data, ab_spec), prototype) - chunk_array: NDBuffer = await self._ab_codec._decode_single(data, ab_spec) + chunk_array = _as_prototype_nd_buffer( + await self._ab_codec._decode_single(data, ab_spec), prototype + ) for aa_codec, aa_spec in zip(reversed(self._aa_codecs), reversed(aa_specs), strict=True): - chunk_array = await aa_codec._decode_single(chunk_array, aa_spec) + chunk_array = _as_prototype_nd_buffer( + await aa_codec._decode_single(chunk_array, aa_spec), prototype + ) return chunk_array @@ -564,24 +590,25 @@ async def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Bu write_empty_chunks=False), matching ChunkTransform.encode_chunk. """ aa_specs, ab_spec = resolve_aa_specs(self._aa_codecs, chunk_spec) + prototype = chunk_spec.prototype - aa_data: NDBuffer = chunk_array + aa_data = _as_prototype_nd_buffer(chunk_array, prototype) for aa_codec, aa_spec in zip(self._aa_codecs, aa_specs, strict=True): aa_result = await aa_codec._encode_single(aa_data, aa_spec) if aa_result is None: return None - aa_data = aa_result + aa_data = _as_prototype_nd_buffer(aa_result, prototype) ab_result = await self._ab_codec._encode_single(aa_data, ab_spec) if ab_result is None: return None - bb_data: Buffer = ab_result + bb_data = _as_prototype_buffer(ab_result, prototype) for bb_codec in self._bb_codecs: bb_result = await bb_codec._encode_single(bb_data, ab_spec) if bb_result is None: return None - bb_data = bb_result + bb_data = _as_prototype_buffer(bb_result, prototype) return bb_data @@ -696,27 +723,34 @@ async def decode_batch( self, chunk_bytes_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], ) -> Iterable[NDBuffer | None]: + # Each codec's input and output is converted to the kind the chunk's + # prototype names, as in `ChunkTransform` (see `_as_prototype_buffer`). chunk_bytes_batch: Iterable[Buffer | None] chunk_bytes_batch, chunk_specs = _unzip2(chunk_bytes_and_specs) + prototypes = [chunk_spec.prototype for chunk_spec in chunk_specs] ( aa_codecs_with_spec, ab_codec_with_spec, bb_codecs_with_spec, ) = self._codecs_with_resolved_metadata_batched(chunk_specs) + chunk_bytes_batch = _as_prototype_buffers(chunk_bytes_batch, prototypes) for bb_codec, chunk_spec_batch in bb_codecs_with_spec[::-1]: - chunk_bytes_batch = await bb_codec.decode( - zip(chunk_bytes_batch, chunk_spec_batch, strict=False) + chunk_bytes_batch = _as_prototype_buffers( + await bb_codec.decode(zip(chunk_bytes_batch, chunk_spec_batch, strict=False)), + prototypes, ) ab_codec, chunk_spec_batch = ab_codec_with_spec - chunk_array_batch = await ab_codec.decode( - zip(chunk_bytes_batch, chunk_spec_batch, strict=False) + chunk_array_batch = _as_prototype_nd_buffers( + await ab_codec.decode(zip(chunk_bytes_batch, chunk_spec_batch, strict=False)), + prototypes, ) for aa_codec, chunk_spec_batch in aa_codecs_with_spec[::-1]: - chunk_array_batch = await aa_codec.decode( - zip(chunk_array_batch, chunk_spec_batch, strict=False) + chunk_array_batch = _as_prototype_nd_buffers( + await aa_codec.decode(zip(chunk_array_batch, chunk_spec_batch, strict=False)), + prototypes, ) return chunk_array_batch @@ -736,24 +770,31 @@ async def encode_batch( self, chunk_arrays_and_specs: Iterable[tuple[NDBuffer | None, ArraySpec]], ) -> Iterable[Buffer | None]: + # Each codec's input and output is converted to the kind the chunk's + # prototype names, as in `ChunkTransform` (see `_as_prototype_buffer`). chunk_array_batch: Iterable[NDBuffer | None] chunk_specs: Iterable[ArraySpec] chunk_array_batch, chunk_specs = _unzip2(chunk_arrays_and_specs) + prototypes = [chunk_spec.prototype for chunk_spec in chunk_specs] + chunk_array_batch = _as_prototype_nd_buffers(chunk_array_batch, prototypes) for aa_codec in self.array_array_codecs: - chunk_array_batch = await aa_codec.encode( - zip(chunk_array_batch, chunk_specs, strict=False) + chunk_array_batch = _as_prototype_nd_buffers( + await aa_codec.encode(zip(chunk_array_batch, chunk_specs, strict=False)), + prototypes, ) chunk_specs = resolve_batched(aa_codec, chunk_specs) - chunk_bytes_batch = await self.array_bytes_codec.encode( - zip(chunk_array_batch, chunk_specs, strict=False) + chunk_bytes_batch = _as_prototype_buffers( + await self.array_bytes_codec.encode(zip(chunk_array_batch, chunk_specs, strict=False)), + prototypes, ) chunk_specs = resolve_batched(self.array_bytes_codec, chunk_specs) for bb_codec in self.bytes_bytes_codecs: - chunk_bytes_batch = await bb_codec.encode( - zip(chunk_bytes_batch, chunk_specs, strict=False) + chunk_bytes_batch = _as_prototype_buffers( + await bb_codec.encode(zip(chunk_bytes_batch, chunk_specs, strict=False)), + prototypes, ) chunk_specs = resolve_batched(bb_codec, chunk_specs) @@ -788,14 +829,15 @@ async def read_batch( for chunk_array, (_, chunk_spec, _, out_selection, _) in zip( chunk_array_batch, batch_info_list, strict=False ): - if chunk_array is not None: - if drop_axes: - chunk_array = chunk_array.squeeze(axis=drop_axes) - out[out_selection] = chunk_array - results.append(GetResult(status="present")) - else: - out[out_selection] = fill_value_or_default(chunk_spec) - results.append(GetResult(status="missing")) + results.append( + scatter_chunk( + chunk_array, + out, + chunk_spec=chunk_spec, + out_selection=out_selection, + drop_axes=drop_axes, + ) + ) return tuple(results) return await _async_read_fallback(self, list(batch_info), out, drop_axes) @@ -1336,14 +1378,15 @@ async def read( for chunk_array, (_, chunk_spec, _, out_selection, _) in zip( chunk_array_batch, batch, strict=False ): - if chunk_array is not None: - if drop_axes: - chunk_array = chunk_array.squeeze(axis=drop_axes) - out[out_selection] = chunk_array - results.append(GetResult(status="present")) - else: - out[out_selection] = fill_value_or_default(chunk_spec) - results.append(GetResult(status="missing")) + results.append( + scatter_chunk( + chunk_array, + out, + chunk_spec=chunk_spec, + out_selection=out_selection, + drop_axes=drop_axes, + ) + ) return tuple(results) return await _async_read_fallback(self, batch, out, drop_axes) diff --git a/tests/test_codecs/test_buffer_prototype.py b/tests/test_codecs/test_buffer_prototype.py index 2876ee0c98..9daa3265c5 100644 --- a/tests/test_codecs/test_buffer_prototype.py +++ b/tests/test_codecs/test_buffer_prototype.py @@ -1,23 +1,26 @@ -"""Codecs build their buffers from the prototype they are given, not from `zarr.config`. +"""Codecs and codec pipelines use the prototype they are given, not `zarr.config`. A read or write takes a `BufferPrototype`; `zarr.config` names another (`buffer` / `ndbuffer`). These tests set the two to different buffer kinds and check that only the given prototype's kind appears: in the array a read returns, in the values the store receives, and in the arrays each codec sees. -The test buffer kind (`TestBuffer` / `NDBufferUsingTestNDArrayLike`) subclasses -the CPU kind, so the tests compare exact types: a value of the configured kind -leaking out would otherwise pass an `isinstance` check. +The second buffer kind is a fake device kind that, like CuPy, refuses to be +mixed with host memory: host buffers refuse to hold its arrays, and its arrays +refuse to be combined with host arrays. So a buffer of the wrong kind fails +here as it would on a GPU, instead of passing silently on the CPU. """ from __future__ import annotations import asyncio +import warnings from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Any, Literal, Self import numcodecs import numpy as np +import numpy.typing as npt import pytest import zarr @@ -32,30 +35,203 @@ from zarr.codecs import numcodecs as zarr_numcodecs from zarr.codecs._v2 import V2Codec from zarr.core.array_spec import ArrayConfig, ArraySpec -from zarr.core.buffer import Buffer, BufferPrototype, NDBuffer, cpu, default_buffer_prototype +from zarr.core.buffer import Buffer, BufferPrototype, NDBuffer, core, cpu, default_buffer_prototype +from zarr.core.chunk_utils import ChunkTransform, scatter_chunk +from zarr.core.codec_pipeline import AsyncChunkTransform, BatchedCodecPipeline from zarr.core.config import config from zarr.core.dtype import get_data_type_from_native_dtype +from zarr.errors import ZarrUserWarning from zarr.registry import fully_qualified_name, register_buffer, register_ndbuffer from zarr.storage import MemoryStore -from zarr.testing.buffer import NDBufferUsingTestNDArrayLike, TestBuffer, TestNDArrayLike if TYPE_CHECKING: + from collections.abc import Iterable + from zarr.abc.codec import Codec -TEST_PROTOTYPE = BufferPrototype(buffer=TestBuffer, nd_buffer=NDBufferUsingTestNDArrayLike) -TEST_CONFIG = { - "buffer": fully_qualified_name(TestBuffer), - "ndbuffer": fully_qualified_name(NDBufferUsingTestNDArrayLike), + +# --- a fake device buffer kind ---------------------------------------------------- + + +def _is_host_array(value: object) -> bool: + return isinstance(value, np.ndarray) and not isinstance(value, DeviceArray) and value.ndim > 0 + + +class DeviceArray(np.ndarray[Any, np.dtype[Any]]): + """An array in fake device memory: combining it with a host array raises, as in CuPy.""" + + def __array_ufunc__(self, ufunc: Any, method: str, *inputs: Any, **kwargs: Any) -> Any: + if any(_is_host_array(x) for x in inputs): + raise TypeError(f"{ufunc} mixes host and device arrays") + args = [x.view(np.ndarray) if isinstance(x, DeviceArray) else x for x in inputs] + if "out" in kwargs: + kwargs["out"] = tuple( + o.view(np.ndarray) if isinstance(o, DeviceArray) else o for o in kwargs["out"] + ) + result = getattr(ufunc, method)(*args, **kwargs) + return result.view(DeviceArray) if isinstance(result, np.ndarray) else result + + def __array_function__(self, func: Any, types: Any, args: Any, kwargs: Any) -> Any: + flat = [a for arg in args for a in (arg if isinstance(arg, list | tuple) else [arg])] + if any(_is_host_array(a) for a in flat): + raise TypeError(f"{func.__name__} mixes host and device arrays") + return super().__array_function__(func, types, args, kwargs) + + +def _to_device(array: npt.ArrayLike) -> Any: + """Copy `array` to fake device memory, as `cupy.asarray` copies a host array.""" + return np.array(array, copy=True).view(DeviceArray) + + +def _to_host(array: Any) -> npt.NDArray[Any]: + """Copy a fake device array to host memory, as `cupy.asnumpy` does.""" + return np.array(array.view(np.ndarray), copy=True) + + +class DeviceBuffer(core.Buffer): + """A `Buffer` in fake device memory, modeled on `zarr.core.buffer.gpu.Buffer`.""" + + def __init__(self, array_like: Any) -> None: + data: Any = array_like if isinstance(array_like, DeviceArray) else _to_device(array_like) + super().__init__(data) + + @classmethod + def create_zero_length(cls) -> Self: + return cls(_to_device(np.array([], dtype="B"))) + + @classmethod + def from_buffer(cls, buffer: core.Buffer) -> Self: + return cls(buffer.as_array_like()) + + @classmethod + def from_bytes(cls, bytes_like: Any) -> Self: + return cls(_to_device(np.frombuffer(bytes_like, dtype="B"))) + + def as_numpy_array(self) -> npt.NDArray[Any]: + return _to_host(self._data) + + def combine(self, others: Iterable[core.Buffer]) -> Self: + data: list[Any] = [self._data] + for other in others: + if not isinstance(other, DeviceBuffer): + # As `zarr.core.buffer.gpu.Buffer.combine` does, by way of its constructor. + warnings.warn( + "combining host memory takes the slow path", ZarrUserWarning, stacklevel=2 + ) + data.append(DeviceBuffer(other.as_array_like())._data) + return self.__class__(np.concatenate(data)) + + +class DeviceNDBuffer(core.NDBuffer): + """An `NDBuffer` in fake device memory, modeled on `zarr.core.buffer.gpu.NDBuffer`.""" + + def __init__(self, array: Any) -> None: + data: Any = array if isinstance(array, DeviceArray) else _to_device(array) + super().__init__(data) + + @classmethod + def create( + cls, + *, + shape: Iterable[int], + dtype: npt.DTypeLike, + order: Literal["C", "F"] = "C", + fill_value: Any | None = None, + ) -> Self: + ret = cls(_to_device(np.empty(tuple(shape), dtype=dtype, order=order))) + if fill_value is not None: + ret.fill(fill_value) + return ret + + @classmethod + def empty( + cls, shape: tuple[int, ...], dtype: npt.DTypeLike, order: Literal["C", "F"] = "C" + ) -> Self: + return cls(_to_device(np.empty(shape, dtype=dtype, order=order))) + + @classmethod + def from_numpy_array(cls, array_like: npt.ArrayLike) -> Self: + return cls(_to_device(array_like)) + + def as_numpy_array(self) -> npt.NDArray[Any]: + return _to_host(self._data) + + def __getitem__(self, key: Any) -> Self: + return self.__class__(self._data.__getitem__(key)) + + def __setitem__(self, key: Any, value: Any) -> None: + if isinstance(value, core.NDBuffer): + value = value.as_ndarray_like() + # Like CuPy, assigning a host array copies it to the device. + self._data.__setitem__(key, value.view(DeviceArray) if _is_host_array(value) else value) + + +DEVICE_PROTOTYPE = BufferPrototype(buffer=DeviceBuffer, nd_buffer=DeviceNDBuffer) +DEVICE_CONFIG = { + "buffer": fully_qualified_name(DeviceBuffer), + "ndbuffer": fully_qualified_name(DeviceNDBuffer), } -PIPELINES = ( - "zarr.core.codec_pipeline.BatchedCodecPipeline", - "zarr.core.codec_pipeline.FusedCodecPipeline", -) + + +class UnusableBuffer(cpu.Buffer): + """A buffer kind that cannot be built, so a buffer made from `zarr.config` fails.""" + + def __init__(self, array_like: Any) -> None: + raise RuntimeError("a buffer was built from zarr.config") + + +class UnusableNDBuffer(cpu.NDBuffer): + """An array buffer kind that cannot be built, so a buffer made from `zarr.config` fails.""" + + def __init__(self, array: Any) -> None: + raise RuntimeError("an array buffer was built from zarr.config") + + +UNUSABLE_CONFIG = { + "buffer": fully_qualified_name(UnusableBuffer), + "ndbuffer": fully_qualified_name(UnusableNDBuffer), +} + + +@pytest.fixture(autouse=True) +def _host_refuses_device_arrays(monkeypatch: pytest.MonkeyPatch) -> None: + """Make host buffers refuse device arrays, as NumPy refuses CuPy arrays. + + Also registers this module's buffer kinds so `zarr.config` can name them. + """ + register_buffer(DeviceBuffer) + register_ndbuffer(DeviceNDBuffer) + register_buffer(UnusableBuffer) + register_ndbuffer(UnusableNDBuffer) + + def refuse(value: object) -> None: + if isinstance(value, DeviceArray | DeviceBuffer | DeviceNDBuffer): + raise TypeError("a host buffer was given device memory") + + buffer_init = cpu.Buffer.__init__ + nd_buffer_init = cpu.NDBuffer.__init__ + nd_buffer_setitem = cpu.NDBuffer.__setitem__ + + def host_buffer_init(self: cpu.Buffer, array_like: Any) -> None: + refuse(array_like) + buffer_init(self, array_like) + + def host_nd_buffer_init(self: cpu.NDBuffer, array: Any) -> None: + refuse(array) + nd_buffer_init(self, array) + + def host_nd_buffer_setitem(self: cpu.NDBuffer, key: Any, value: Any) -> None: + refuse(value._data if isinstance(value, core.NDBuffer) else value) + nd_buffer_setitem(self, key, value) + + monkeypatch.setattr(cpu.Buffer, "__init__", host_buffer_init) + monkeypatch.setattr(cpu.NDBuffer, "__init__", host_nd_buffer_init) + monkeypatch.setattr(cpu.NDBuffer, "__setitem__", host_nd_buffer_setitem) @dataclass(frozen=True) class Direction: - """A prototype to call with, and a `zarr.config` naming a different buffer kind.""" + """A prototype to call with, and the buffer kind `zarr.config` names.""" name: str prototype: BufferPrototype @@ -64,17 +240,18 @@ class Direction: DIRECTIONS = ( - # The configured kind is the test kind; the call asks for the CPU kind. - Direction("config-test-call-cpu", cpu.buffer_prototype, TEST_CONFIG, np.ndarray), - # The configured kind is the default CPU kind; the call asks for the test kind. - Direction("config-cpu-call-test", TEST_PROTOTYPE, {}, TestNDArrayLike), + Direction("config-device-call-host", cpu.buffer_prototype, DEVICE_CONFIG, np.ndarray), + Direction("config-host-call-device", DEVICE_PROTOTYPE, {}, DeviceArray), + # The configured prototype, as in GPU mode before this change: nothing to convert. + Direction("config-device-call-device", DEVICE_PROTOTYPE, DEVICE_CONFIG, DeviceArray), +) +PIPELINES = ( + "zarr.core.codec_pipeline.BatchedCodecPipeline", + "zarr.core.codec_pipeline.FusedCodecPipeline", ) -@pytest.fixture(autouse=True) -def _register_test_buffers() -> None: - register_buffer(TestBuffer) - register_ndbuffer(NDBufferUsingTestNDArrayLike) +# --- codecs of the shapes codecs from other packages take -------------------------- class RecordingStore(MemoryStore): @@ -98,73 +275,70 @@ def set_sync(self, key: str, value: Buffer) -> None: @dataclass(frozen=True) -class ExpectPrototypeCodec(ArrayArrayCodec): - """A no-op codec that fails unless its input has the exact type the spec's prototype names. +class RecordingCodec: + """Records each direction it runs in, so a test can tell the codec was not skipped.""" - Placed first in a codec chain, it sees the array the pipeline hands to the - codecs on encode, and the array the rest of the chain decodes on decode. - """ + calls: list[str] = field(default_factory=list, compare=False, hash=False) is_fixed_size = True - def to_dict(self) -> dict[str, Any]: - return {"name": "test-expect-prototype"} - def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: return input_byte_length - def _check(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + +@dataclass(frozen=True) +class ExpectPrototypeCodec(RecordingCodec, ArrayArrayCodec): + """A no-op codec that fails unless its input has the exact type the spec's prototype names.""" + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-expect-prototype"} + + def _check(self, chunk_array: NDBuffer, chunk_spec: ArraySpec, direction: str) -> NDBuffer: + self.calls.append(direction) assert type(chunk_array) is chunk_spec.prototype.nd_buffer, ( f"expected {chunk_spec.prototype.nd_buffer}, got {type(chunk_array)}" ) return chunk_array - _encode_sync = _check - _decode_sync = _check + def _encode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._check(chunk_array, chunk_spec, "encode") + + def _decode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._check(chunk_array, chunk_spec, "decode") async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: - return self._check(chunk_array, chunk_spec) + return self._encode_sync(chunk_array, chunk_spec) async def _decode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: - return self._check(chunk_array, chunk_spec) + return self._decode_sync(chunk_array, chunk_spec) @dataclass(frozen=True) -class AsyncOnlyCodec(BytesBytesCodec): - """A no-op codec with only the async interface, like codecs written before the sync one.""" +class AsyncOnlyCodec(RecordingCodec, BytesBytesCodec): + """A no-op codec with only the async interface, which builds its output from `zarr.config`. - is_fixed_size = True + Like a codec written before both the sync interface and prototypes. + """ def to_dict(self) -> dict[str, Any]: return {"name": "test-async-only"} - def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: - return input_byte_length - async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: - return chunk_bytes + self.calls.append("encode") + return default_buffer_prototype().buffer.from_bytes(chunk_bytes.to_bytes()) async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: - return chunk_bytes + self.calls.append("decode") + return default_buffer_prototype().buffer.from_bytes(chunk_bytes.to_bytes()) @dataclass(frozen=True) -class ConfigBufferCodec(BytesBytesCodec): - """A no-op codec that ignores `chunk_spec.prototype` and builds its output from `zarr.config`. - - Stands for a codec written outside zarr that predates prototypes. It records - that it ran, so a test can tell it was not skipped. - """ - - is_fixed_size = True - calls: list[str] = field(default_factory=list, compare=False, hash=False) +class ConfigBufferCodec(RecordingCodec, BytesBytesCodec): + """A no-op codec that ignores `chunk_spec.prototype` and builds its output from `zarr.config`.""" def to_dict(self) -> dict[str, Any]: return {"name": "test-config-buffer"} - def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: - return input_byte_length - def _convert(self, chunk_bytes: Buffer, direction: str) -> Buffer: self.calls.append(direction) return default_buffer_prototype().buffer.from_bytes(chunk_bytes.to_bytes()) @@ -182,8 +356,38 @@ async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Bu return self._decode_sync(chunk_bytes, chunk_spec) +@dataclass(frozen=True) +class ConfigArrayCodec(RecordingCodec, ArrayArrayCodec): + """A no-op codec that ignores `chunk_spec.prototype` and builds its output from `zarr.config`.""" + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-config-array"} + + def _convert(self, chunk_array: NDBuffer, direction: str) -> NDBuffer: + self.calls.append(direction) + return default_buffer_prototype().nd_buffer.from_numpy_array(chunk_array.as_numpy_array()) + + def _encode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._convert(chunk_array, "encode") + + def _decode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._convert(chunk_array, "decode") + + async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._encode_sync(chunk_array, chunk_spec) + + async def _decode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._decode_sync(chunk_array, chunk_spec) + + def _zarr_chain() -> list[Codec]: - return [ExpectPrototypeCodec(), TransposeCodec(order=(1, 0)), BytesCodec(), GzipCodec()] + return [ + ExpectPrototypeCodec(), + TransposeCodec(order=(1, 0)), + BytesCodec(), + GzipCodec(), + Crc32cCodec(), + ] def _numcodecs_chain() -> list[Codec]: @@ -197,11 +401,42 @@ def _numcodecs_chain() -> list[Codec]: def _async_only_chain() -> list[Codec]: - return [ExpectPrototypeCodec(), BytesCodec(), AsyncOnlyCodec(), Crc32cCodec()] + """The async-only codec both inside the chain and at its end.""" + return [ExpectPrototypeCodec(), BytesCodec(), AsyncOnlyCodec(), Crc32cCodec(), AsyncOnlyCodec()] -CHAINS = {"zarr": _zarr_chain, "numcodecs": _numcodecs_chain, "async-only": _async_only_chain} -Layout = Literal["v3", "v3-sharded", "v3-nested-sharded", "v2"] +def _config_chain() -> list[Codec]: + """Codecs that ignore the prototype, both inside the chain and at each end.""" + return [ + ExpectPrototypeCodec(), + ConfigArrayCodec(), + BytesCodec(), + ConfigBufferCodec(), + GzipCodec(), + ConfigBufferCodec(), + ] + + +def _no_chain() -> list[Codec]: + """For a v2 array, which takes numcodecs filters and compressors instead (see `_create`).""" + return [] + + +CHAINS = { + "zarr": _zarr_chain, + "numcodecs": _numcodecs_chain, + "async-only": _async_only_chain, + "ignores-prototype": _config_chain, +} +Layout = Literal["v3", "v3-sharded", "v3-sharded-index-at-start", "v3-nested-sharded", "v2"] +LAYOUT_CHAINS = [ + *( + (layout, chain) + for layout in ("v3", "v3-sharded", "v3-sharded-index-at-start", "v3-nested-sharded") + for chain in CHAINS + ), + ("v2", "numcodecs-filters"), +] def _chain_kwargs(chain: list[Codec]) -> dict[str, Any]: @@ -214,7 +449,11 @@ def _chain_kwargs(chain: list[Codec]) -> dict[str, Any]: def _create(store: MemoryStore, layout: Layout, chain: list[Codec]) -> zarr.Array[Any]: - """An (8, 8) int32 array of the given layout, with 2x2 chunks inside 4x4 shards.""" + """An (8, 8) int32 array of the given layout, with 2x2 chunks inside 4x4 shards. + + `v3-sharded-index-at-start` also encodes the shard index with `BytesCodec` + alone: no checksum codec copies the index bytes to the host on the way. + """ common: dict[str, Any] = {"shape": (8, 8), "dtype": "int32", "fill_value": 0} if layout == "v2": return zarr.create_array( @@ -227,43 +466,40 @@ def _create(store: MemoryStore, layout: Layout, chain: list[Codec]) -> zarr.Arra ) if layout == "v3": return zarr.create_array(store, chunks=(2, 2), **_chain_kwargs(chain), **common) - inner: list[Codec] = chain + sharding: dict[str, Any] = {"chunk_shape": (2, 2), "codecs": chain} if layout == "v3-nested-sharded": - inner = [ShardingCodec(chunk_shape=(1, 1), codecs=chain)] + sharding["codecs"] = [ShardingCodec(chunk_shape=(1, 1), codecs=chain)] + if layout == "v3-sharded-index-at-start": + sharding["index_codecs"] = [BytesCodec()] + sharding["index_location"] = "start" return zarr.create_array( - store, - chunks=(4, 4), - serializer=ShardingCodec(chunk_shape=(2, 2), codecs=inner), - compressors=None, - **common, + store, chunks=(4, 4), serializer=ShardingCodec(**sharding), compressors=None, **common ) async def _round_trip( array: zarr.Array[Any], prototype: BufferPrototype -) -> list[tuple[Any, np.ndarray[Any, Any]]]: - """Write all of `array`, then part of it, then read all and part of it back. +) -> list[tuple[Any, npt.NDArray[Any]]]: + """Write part of the empty `array`, then all of it, then part again; read all and part back. - Returns each read result with its expected value. The partial write and read - each cross inner-chunk and shard boundaries. + Returns each read result with its expected value. The partial writes and read + each cross inner-chunk and shard boundaries; the first lands in absent shards. """ async_array = array._async_array + region = (slice(1, 5), slice(3, 6)) + patch = np.full((4, 3), -7, dtype="int32") expected = np.arange(64, dtype="int32").reshape(8, 8) + await async_array.setitem(region, patch, prototype=prototype) await async_array.setitem((slice(None), slice(None)), expected, prototype=prototype) - await async_array.setitem( - (slice(1, 5), slice(3, 6)), np.full((4, 3), -7, dtype="int32"), prototype=prototype - ) + await async_array.setitem(region, patch, prototype=prototype) expected[1:5, 3:6] = -7 full = await async_array.getitem((slice(None), slice(None)), prototype=prototype) part = await async_array.getitem((slice(1, 6), slice(2, 7)), prototype=prototype) return [(full, expected), (part, expected[1:6, 2:7])] -# A v2 array takes numcodecs filters and compressors, not a codec chain (see `_create`). -LAYOUT_CHAINS = [ - *((layout, chain) for layout in ("v3", "v3-sharded", "v3-nested-sharded") for chain in CHAINS), - ("v2", "numcodecs"), -] +def _host(array: Any) -> npt.NDArray[Any]: + return _to_host(array) if isinstance(array, DeviceArray) else np.asarray(array) @pytest.mark.parametrize("pipeline", PIPELINES) @@ -274,49 +510,27 @@ def test_codecs_use_the_given_prototype( ) -> None: """Reads and writes produce the given prototype's buffer kind, whatever `zarr.config` names. - The `numcodecs` chain uses zarr's numcodecs wrappers and the `async-only` - chain a codec with no sync interface, both of the shape codecs from other - packages take. v2 arrays always use numcodecs filters and compressors. - """ - store = RecordingStore() - with config.set({**direction.buffer_config, "codec_pipeline.path": pipeline}): - array = _create(store, layout, CHAINS[chain]()) - results = asyncio.run(_round_trip(array, direction.prototype)) - for got, expected in results: - assert type(got) is direction.array_type - np.testing.assert_array_equal(got, expected) - assert store.chunk_value_types == {direction.prototype.buffer} - - -@pytest.mark.parametrize("pipeline", PIPELINES) -@pytest.mark.parametrize("direction", DIRECTIONS, ids=lambda d: d.name) -def test_sharding_converts_buffers_from_codecs_that_ignore_the_prototype( - pipeline: str, direction: Direction -) -> None: - """A shard gets the given prototype's buffer kind even when an inner codec ignores it. - - `ConfigBufferCodec` returns buffers of the configured kind. The sharding codec - converts them before they reach the shard it writes or the reads it serves. + The chains cover zarr's codecs, zarr's numcodecs wrappers, a codec with no sync + interface, and codecs that ignore the prototype and build their buffers from + `zarr.config`; codecs from other packages take these shapes. """ - codec = ConfigBufferCodec() + codecs = _no_chain() if layout == "v2" else CHAINS[chain]() store = RecordingStore() with config.set({**direction.buffer_config, "codec_pipeline.path": pipeline}): - array = _create(store, "v3-sharded", [BytesCodec(), codec]) + array = _create(store, layout, codecs) results = asyncio.run(_round_trip(array, direction.prototype)) - for got, expected in results: - assert type(got) is direction.array_type - np.testing.assert_array_equal(got, expected) + for got, expected in results: + assert type(got) is direction.array_type + np.testing.assert_array_equal(_host(got), expected) assert store.chunk_value_types == {direction.prototype.buffer} - assert {"encode", "decode"} <= set(codec.calls) + for codec in codecs: + if isinstance(codec, RecordingCodec): + assert {"encode", "decode"} <= set(codec.calls), codec @pytest.mark.parametrize("direction", DIRECTIONS, ids=lambda d: d.name) def test_v2_codec_decodes_into_the_given_prototype(direction: Direction) -> None: - """`V2Codec` returns the spec's prototype's array kind, not the configured one. - - The pipeline copies a decoded chunk into an output buffer of the call's kind, - so an array read alone would not show a decoded chunk of the wrong kind. - """ + """`V2Codec` returns the spec's prototype's array kind, not the configured one.""" zdtype = get_data_type_from_native_dtype(np.dtype("int32")) spec = ArraySpec( shape=(2, 2), @@ -326,12 +540,122 @@ def test_v2_codec_decodes_into_the_given_prototype(direction: Direction) -> None prototype=direction.prototype, ) codec = V2Codec(filters=(numcodecs.Delta(dtype=" None: + """With a prototype given and codecs that follow it, no buffer is built from `zarr.config`. + + `zarr.config` names a buffer kind that cannot be built; reads and writes still work. + """ + codecs = _no_chain() if layout == "v2" else CHAINS[chain]() + with config.set({"codec_pipeline.path": pipeline}): + array = _create(RecordingStore(), layout, codecs) + with config.set({**UNUSABLE_CONFIG, "codec_pipeline.path": pipeline}): + results = asyncio.run(_round_trip(array, prototype)) + for got, expected in results: + np.testing.assert_array_equal(_host(got), expected) + + +def _other_kind(prototype: BufferPrototype) -> BufferPrototype: + return DEVICE_PROTOTYPE if prototype is cpu.buffer_prototype else cpu.buffer_prototype + + +def _int32_spec(prototype: BufferPrototype) -> ArraySpec: + zdtype = get_data_type_from_native_dtype(np.dtype("int32")) + return ArraySpec( + shape=(2, 2), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig.from_dict({}), + prototype=prototype, + ) + + +async def _run_chain( + runner: str, direction: Literal["encode", "decode"], chunk: Any, spec: ArraySpec +) -> Any: + codecs = (BytesCodec(),) + if runner == "chunk-transform": + transform = ChunkTransform(codecs=codecs) + if direction == "encode": + return transform.encode_chunk(chunk, spec) + return transform.decode_chunk(chunk, spec) + if runner == "async-chunk-transform": + async_transform = AsyncChunkTransform(codecs=codecs) + if direction == "encode": + return await async_transform.encode_chunk(chunk, spec) + return await async_transform.decode_chunk(chunk, spec) + pipeline = BatchedCodecPipeline.from_codecs(codecs) + if direction == "encode": + return next(iter(await pipeline.encode([(chunk, spec)]))) + return next(iter(await pipeline.decode([(chunk, spec)]))) + + +@pytest.mark.parametrize("runner", ["chunk-transform", "async-chunk-transform", "batched-pipeline"]) +@pytest.mark.parametrize( + "prototype", [cpu.buffer_prototype, DEVICE_PROTOTYPE], ids=["host", "device"] +) +def test_codec_chains_convert_input_of_another_kind( + runner: str, prototype: BufferPrototype +) -> None: + """A chain given a chunk of another buffer kind than its spec names converts it first. + + The shard index takes this route: its bytes arrive in the shard's kind, and + its spec names host memory. + """ + spec = _int32_spec(prototype) + data = np.arange(4, dtype="int32").reshape(2, 2) + other = _other_kind(prototype) + encoded = asyncio.run( + _run_chain(runner, "encode", other.nd_buffer.from_numpy_array(data), spec) + ) + assert type(encoded) is prototype.buffer + decoded = asyncio.run( + _run_chain(runner, "decode", other.buffer.from_bytes(encoded.to_bytes()), spec) + ) + assert type(decoded) is prototype.nd_buffer + np.testing.assert_array_equal(decoded.as_numpy_array(), data) + + +@pytest.mark.parametrize( + "prototype", [cpu.buffer_prototype, DEVICE_PROTOTYPE], ids=["host", "device"] +) +def test_scatter_chunk_converts_a_chunk_of_another_kind(prototype: BufferPrototype) -> None: + """`scatter_chunk` converts a decoded chunk to the output's kind before assigning it. + + A partial decode hands the array-bytes codec's output straight to it. + """ + spec = _int32_spec(prototype) + data = np.arange(4, dtype="int32").reshape(2, 2) + out = prototype.nd_buffer.create(shape=(2, 2), dtype="int32", fill_value=0) + chunk = _other_kind(prototype).nd_buffer.from_numpy_array(data) + scatter_chunk( + chunk, out, chunk_spec=spec, out_selection=(slice(None), slice(None)), drop_axes=() + ) + np.testing.assert_array_equal(out.as_numpy_array(), data) From e4a63ff9e501429fd0e9510c9590df2d946cb508 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 12:57:08 +0100 Subject: [PATCH 3/7] fix(codecs): pass non-buffer codec output through and convert per stage Round-2 review fixes: - `_as_prototype_buffer`/`_as_prototype_nd_buffer` convert only `Buffer` and `NDBuffer` instances; anything else a codec returns (a NumPy array, `bytes`) passes through unchanged, as before. Codecs from other packages that return raw arrays (e.g. icon-ch-vzarr's `EccodesCodec`) failed every read. - Conversion goes through `from_bytes(as_buffer_like())`, so a host-to-GPU conversion takes no slow-path warning and host kinds convert without a copy; the shard index uses the same helper. - Each codec gets its input as the kind its own spec names, and the chain's output is converted to the caller's spec, instead of converting every stage to the caller's prototype. - `test_sharding_use_of_gpu_prototype` no longer expects a slow-path warning: the shard index no longer round-trips through the GPU kind. - `fill_value_or_default` stays importable from `zarr.core.codec_pipeline`. - The extending guide states the prototype contract for codecs. The tests add codecs that return raw arrays and bytes, a codec that names another prototype for the rest of the chain, bytes-side prototype checks next to each prototype-ignoring codec, and restrict numcodecs (host-only) cases to host prototypes. All 48 single-site reversions of the change fail a test. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- docs/user-guide/extending.md | 11 + src/zarr/codecs/sharding.py | 8 +- src/zarr/core/buffer/core.py | 39 +-- src/zarr/core/chunk_utils.py | 38 +-- src/zarr/core/codec_pipeline.py | 133 ++++++---- tests/test_buffer.py | 21 +- tests/test_codecs/test_buffer_prototype.py | 293 ++++++++++++++++++--- 7 files changed, 408 insertions(+), 135 deletions(-) diff --git a/docs/user-guide/extending.md b/docs/user-guide/extending.md index bf0eb442c9..0867c432e2 100644 --- a/docs/user-guide/extending.md +++ b/docs/user-guide/extending.md @@ -48,6 +48,17 @@ Custom codecs should also implement the following methods: - `evolve_from_array_spec` (optional), which can be useful for automatically filling in codec configuration metadata from the array metadata. +A codec receives the chunk's buffer kind (host or GPU memory, for instance) in +`chunk_spec.prototype`, and should build the buffers it returns from that prototype +(`chunk_spec.prototype.buffer` and `chunk_spec.prototype.nd_buffer`), not from +[`zarr.config`][]: a read or write may ask for a different kind than the one configured. +The codec pipelines hand each codec its input as the kind its `chunk_spec.prototype` +names, and convert a `Buffer` or `NDBuffer` of another kind that a codec returns, +at the cost of a copy. A cross-kind `NDBuffer` conversion goes through +`as_numpy_array` and `from_numpy_array`, so a custom array buffer class must support both. +Codecs should return `Buffer` and `NDBuffer` instances; any other value is passed on +unchanged. + To use custom codecs in Zarr, they need to be registered using the [entrypoint mechanism](https://packaging.python.org/en/latest/specifications/entry-points/). Commonly, entrypoints are declared in the `pyproject.toml` of your package under the diff --git a/src/zarr/codecs/sharding.py b/src/zarr/codecs/sharding.py index 0838857dee..9ed4cf8319 100644 --- a/src/zarr/codecs/sharding.py +++ b/src/zarr/codecs/sharding.py @@ -35,6 +35,7 @@ NDBuffer, numpy_buffer_prototype, ) +from zarr.core.buffer.core import _as_prototype_buffer from zarr.core.chunk_grids import ChunkGrid from zarr.core.chunk_utils import ( ChunkTransform, @@ -1006,11 +1007,8 @@ def _assemble_shard( "encoded shard index size does not match _shard_index_size; " "variable-size index codecs are not supported" ) - # The index is encoded in host memory (see `_get_index_chunk_spec`). Copy it - # through bytes rather than `from_buffer`: it is a few bytes per chunk, - # and a host-to-device `from_buffer` warns about taking the slow path. - if not isinstance(index_bytes, buffer_prototype.buffer): - index_bytes = buffer_prototype.buffer.from_bytes(index_bytes.to_bytes()) + # The index is encoded in host memory (see `_get_index_chunk_spec`). + index_bytes = _as_prototype_buffer(index_bytes, buffer_prototype) if self.index_location == "start": buffers.insert(0, index_bytes) else: diff --git a/src/zarr/core/buffer/core.py b/src/zarr/core/buffer/core.py index 6952edb0b5..ec6dde86d8 100644 --- a/src/zarr/core/buffer/core.py +++ b/src/zarr/core/buffer/core.py @@ -598,30 +598,37 @@ class BufferPrototype(NamedTuple): nd_buffer: type[NDBuffer] -def _as_prototype_buffer(buffer: Buffer, prototype: BufferPrototype) -> Buffer: - """Return `buffer` as an instance of `prototype.buffer`, converting only on a mismatch. +def _as_prototype_buffer[T](value: T, prototype: BufferPrototype) -> T: + """Return a `Buffer` of another kind as a `prototype.buffer`; return anything else unchanged. - The codec pipelines pass every codec's input and output through this (and - `_as_prototype_nd_buffer`), so a codec that builds its buffers some other - way than from `chunk_spec.prototype`, for instance from `zarr.config`, + The codec pipelines pass each codec's input, and the chain's output, through + this (and `_as_prototype_nd_buffer`), so a codec that builds its buffers some + other way than from `chunk_spec.prototype`, for instance from `zarr.config`, cannot hand a buffer of another kind (host or device memory) to the next - codec, the store, or the caller. + codec, the store, or the caller. A value that is not a `Buffer` at all, such + as `bytes` from a codec that predates the `Buffer` contract, is passed on + unchanged, as it was before these conversions existed. """ - if isinstance(buffer, prototype.buffer): - return buffer - return prototype.buffer.from_buffer(buffer) + if isinstance(value, Buffer) and not isinstance(value, prototype.buffer): + # Through host memory with `from_bytes`, not `from_buffer`: the GPU + # buffer's `from_buffer` warns about a slow path when given host memory, + # and a host buffer's `as_buffer_like` is a view, so host kinds convert + # without a copy. + return cast("T", prototype.buffer.from_bytes(value.as_buffer_like())) + return value -def _as_prototype_nd_buffer(nd_buffer: NDBuffer, prototype: BufferPrototype) -> NDBuffer: - """Return `nd_buffer` as an instance of `prototype.nd_buffer`, converting only on a mismatch. +def _as_prototype_nd_buffer[T](value: T, prototype: BufferPrototype) -> T: + """Return an `NDBuffer` of another kind as a `prototype.nd_buffer`; return anything else unchanged. - `NDBuffer` has no `from_buffer`; the conversion goes through a NumPy array - in host memory. It only runs for a codec that ignores `chunk_spec.prototype`. + `NDBuffer` has no `from_buffer`; the conversion goes through a NumPy array in + host memory. A value that is not an `NDBuffer`, such as a raw NumPy array + from a codec that predates the `NDBuffer` contract, is passed on unchanged. See `_as_prototype_buffer`. """ - if isinstance(nd_buffer, prototype.nd_buffer): - return nd_buffer - return prototype.nd_buffer.from_numpy_array(nd_buffer.as_numpy_array()) + if isinstance(value, NDBuffer) and not isinstance(value, prototype.nd_buffer): + return cast("T", prototype.nd_buffer.from_numpy_array(value.as_numpy_array())) + return value # The default buffer prototype used throughout the Zarr codebase. diff --git a/src/zarr/core/chunk_utils.py b/src/zarr/core/chunk_utils.py index 3cf4c9aab0..89411addb1 100644 --- a/src/zarr/core/chunk_utils.py +++ b/src/zarr/core/chunk_utils.py @@ -323,20 +323,21 @@ def decode_chunk(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: configuration for this chunk. """ aa_specs, ab_spec = self._resolve_specs(chunk_spec) - prototype = chunk_spec.prototype - data = _as_prototype_buffer(chunk_bytes, prototype) + data = chunk_bytes for bb_codec in reversed(self._bb_codecs): - data = _as_prototype_buffer(bb_codec._decode_sync(data, ab_spec), prototype) + data = bb_codec._decode_sync(_as_prototype_buffer(data, ab_spec.prototype), ab_spec) - chunk_array = _as_prototype_nd_buffer(self._ab_codec._decode_sync(data, ab_spec), prototype) + chunk_array = self._ab_codec._decode_sync( + _as_prototype_buffer(data, ab_spec.prototype), ab_spec + ) for aa_codec, aa_spec in zip(reversed(self._aa_codecs), reversed(aa_specs), strict=True): - chunk_array = _as_prototype_nd_buffer( - aa_codec._decode_sync(chunk_array, aa_spec), prototype + chunk_array = aa_codec._decode_sync( + _as_prototype_nd_buffer(chunk_array, aa_spec.prototype), aa_spec ) - return chunk_array + return _as_prototype_nd_buffer(chunk_array, chunk_spec.prototype) def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None: """Encode a single chunk through the full codec chain, synchronously. @@ -352,27 +353,32 @@ def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | configuration for this chunk. """ aa_specs, ab_spec = self._resolve_specs(chunk_spec) - prototype = chunk_spec.prototype - aa_data = _as_prototype_nd_buffer(chunk_array, prototype) + aa_data = chunk_array for aa_codec, aa_spec in zip(self._aa_codecs, aa_specs, strict=True): - aa_result = aa_codec._encode_sync(aa_data, aa_spec) + aa_result = aa_codec._encode_sync( + _as_prototype_nd_buffer(aa_data, aa_spec.prototype), aa_spec + ) if aa_result is None: return None - aa_data = _as_prototype_nd_buffer(aa_result, prototype) + aa_data = aa_result - ab_result = self._ab_codec._encode_sync(aa_data, ab_spec) + ab_result = self._ab_codec._encode_sync( + _as_prototype_nd_buffer(aa_data, ab_spec.prototype), ab_spec + ) if ab_result is None: return None - bb_data = _as_prototype_buffer(ab_result, prototype) + bb_data = ab_result for bb_codec in self._bb_codecs: - bb_result = bb_codec._encode_sync(bb_data, ab_spec) + bb_result = bb_codec._encode_sync( + _as_prototype_buffer(bb_data, ab_spec.prototype), ab_spec + ) if bb_result is None: return None - bb_data = _as_prototype_buffer(bb_result, prototype) + bb_data = bb_result - return bb_data + return _as_prototype_buffer(bb_data, chunk_spec.prototype) def compute_encoded_size(self, byte_length: int, array_spec: ArraySpec) -> int: for codec in self.codecs: diff --git a/src/zarr/core/codec_pipeline.py b/src/zarr/core/codec_pipeline.py index dd27096be7..f3f3c490c7 100644 --- a/src/zarr/core/codec_pipeline.py +++ b/src/zarr/core/codec_pipeline.py @@ -26,6 +26,7 @@ chunk_is_empty, decode_and_scatter_chunk, evolve_codecs, + fill_value_or_default, # noqa: F401 # still importable from this module merge_and_encode_chunk, scatter_chunk, ) @@ -129,22 +130,22 @@ def _unzip2[T, U](iterable: Iterable[tuple[T, U]]) -> tuple[list[T], list[U]]: def _as_prototype_buffers( - chunks: Iterable[Buffer | None], prototypes: list[BufferPrototype] + chunks: Iterable[Buffer | None], specs: Iterable[ArraySpec] ) -> list[Buffer | None]: - """`_as_prototype_buffer` over a batch of chunks; a missing chunk stays `None`.""" + """`_as_prototype_buffer` over a batch of chunks, each to its spec's prototype.""" return [ - None if chunk is None else _as_prototype_buffer(chunk, prototype) - for chunk, prototype in zip(chunks, prototypes, strict=True) + _as_prototype_buffer(chunk, spec.prototype) + for chunk, spec in zip(chunks, specs, strict=True) ] def _as_prototype_nd_buffers( - chunks: Iterable[NDBuffer | None], prototypes: list[BufferPrototype] + chunks: Iterable[NDBuffer | None], specs: Iterable[ArraySpec] ) -> list[NDBuffer | None]: - """`_as_prototype_nd_buffer` over a batch of chunks; a missing chunk stays `None`.""" + """`_as_prototype_nd_buffer` over a batch of chunks, each to its spec's prototype.""" return [ - None if chunk is None else _as_prototype_nd_buffer(chunk, prototype) - for chunk, prototype in zip(chunks, prototypes, strict=True) + _as_prototype_nd_buffer(chunk, spec.prototype) + for chunk, spec in zip(chunks, specs, strict=True) ] @@ -566,22 +567,23 @@ def __post_init__(self) -> None: async def decode_chunk(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: """Decode one chunk through the chain (bb -> ab -> aa), async.""" aa_specs, ab_spec = resolve_aa_specs(self._aa_codecs, chunk_spec) - prototype = chunk_spec.prototype - data = _as_prototype_buffer(chunk_bytes, prototype) + data = chunk_bytes for bb_codec in reversed(self._bb_codecs): - data = _as_prototype_buffer(await bb_codec._decode_single(data, ab_spec), prototype) + data = await bb_codec._decode_single( + _as_prototype_buffer(data, ab_spec.prototype), ab_spec + ) - chunk_array = _as_prototype_nd_buffer( - await self._ab_codec._decode_single(data, ab_spec), prototype + chunk_array = await self._ab_codec._decode_single( + _as_prototype_buffer(data, ab_spec.prototype), ab_spec ) for aa_codec, aa_spec in zip(reversed(self._aa_codecs), reversed(aa_specs), strict=True): - chunk_array = _as_prototype_nd_buffer( - await aa_codec._decode_single(chunk_array, aa_spec), prototype + chunk_array = await aa_codec._decode_single( + _as_prototype_nd_buffer(chunk_array, aa_spec.prototype), aa_spec ) - return chunk_array + return _as_prototype_nd_buffer(chunk_array, chunk_spec.prototype) async def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | None: """Encode one chunk through the chain (aa -> ab -> bb), async. @@ -590,27 +592,32 @@ async def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Bu write_empty_chunks=False), matching ChunkTransform.encode_chunk. """ aa_specs, ab_spec = resolve_aa_specs(self._aa_codecs, chunk_spec) - prototype = chunk_spec.prototype - aa_data = _as_prototype_nd_buffer(chunk_array, prototype) + aa_data = chunk_array for aa_codec, aa_spec in zip(self._aa_codecs, aa_specs, strict=True): - aa_result = await aa_codec._encode_single(aa_data, aa_spec) + aa_result = await aa_codec._encode_single( + _as_prototype_nd_buffer(aa_data, aa_spec.prototype), aa_spec + ) if aa_result is None: return None - aa_data = _as_prototype_nd_buffer(aa_result, prototype) + aa_data = aa_result - ab_result = await self._ab_codec._encode_single(aa_data, ab_spec) + ab_result = await self._ab_codec._encode_single( + _as_prototype_nd_buffer(aa_data, ab_spec.prototype), ab_spec + ) if ab_result is None: return None - bb_data = _as_prototype_buffer(ab_result, prototype) + bb_data = ab_result for bb_codec in self._bb_codecs: - bb_result = await bb_codec._encode_single(bb_data, ab_spec) + bb_result = await bb_codec._encode_single( + _as_prototype_buffer(bb_data, ab_spec.prototype), ab_spec + ) if bb_result is None: return None - bb_data = _as_prototype_buffer(bb_result, prototype) + bb_data = bb_result - return bb_data + return _as_prototype_buffer(bb_data, chunk_spec.prototype) @dataclass(frozen=True) @@ -723,37 +730,45 @@ async def decode_batch( self, chunk_bytes_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], ) -> Iterable[NDBuffer | None]: - # Each codec's input and output is converted to the kind the chunk's - # prototype names, as in `ChunkTransform` (see `_as_prototype_buffer`). + # Each codec gets its input as the buffer kind its own spec's prototype + # names, and the caller gets the output as the kind its spec names, as in + # `ChunkTransform` (see `_as_prototype_buffer`). chunk_bytes_batch: Iterable[Buffer | None] chunk_bytes_batch, chunk_specs = _unzip2(chunk_bytes_and_specs) - prototypes = [chunk_spec.prototype for chunk_spec in chunk_specs] ( aa_codecs_with_spec, ab_codec_with_spec, bb_codecs_with_spec, ) = self._codecs_with_resolved_metadata_batched(chunk_specs) - chunk_bytes_batch = _as_prototype_buffers(chunk_bytes_batch, prototypes) for bb_codec, chunk_spec_batch in bb_codecs_with_spec[::-1]: - chunk_bytes_batch = _as_prototype_buffers( - await bb_codec.decode(zip(chunk_bytes_batch, chunk_spec_batch, strict=False)), - prototypes, + chunk_bytes_batch = await bb_codec.decode( + zip( + _as_prototype_buffers(chunk_bytes_batch, chunk_spec_batch), + chunk_spec_batch, + strict=False, + ) ) ab_codec, chunk_spec_batch = ab_codec_with_spec - chunk_array_batch = _as_prototype_nd_buffers( - await ab_codec.decode(zip(chunk_bytes_batch, chunk_spec_batch, strict=False)), - prototypes, + chunk_array_batch = await ab_codec.decode( + zip( + _as_prototype_buffers(chunk_bytes_batch, chunk_spec_batch), + chunk_spec_batch, + strict=False, + ) ) for aa_codec, chunk_spec_batch in aa_codecs_with_spec[::-1]: - chunk_array_batch = _as_prototype_nd_buffers( - await aa_codec.decode(zip(chunk_array_batch, chunk_spec_batch, strict=False)), - prototypes, + chunk_array_batch = await aa_codec.decode( + zip( + _as_prototype_nd_buffers(chunk_array_batch, chunk_spec_batch), + chunk_spec_batch, + strict=False, + ) ) - return chunk_array_batch + return _as_prototype_nd_buffers(chunk_array_batch, chunk_specs) async def decode_partial_batch( self, @@ -770,35 +785,39 @@ async def encode_batch( self, chunk_arrays_and_specs: Iterable[tuple[NDBuffer | None, ArraySpec]], ) -> Iterable[Buffer | None]: - # Each codec's input and output is converted to the kind the chunk's - # prototype names, as in `ChunkTransform` (see `_as_prototype_buffer`). + # Each codec gets its input as the buffer kind its own spec's prototype + # names, and the caller gets the output as the kind its spec names, as in + # `ChunkTransform` (see `_as_prototype_buffer`). chunk_array_batch: Iterable[NDBuffer | None] - chunk_specs: Iterable[ArraySpec] + chunk_bytes_batch: Iterable[Buffer | None] + stage_specs: Iterable[ArraySpec] chunk_array_batch, chunk_specs = _unzip2(chunk_arrays_and_specs) - prototypes = [chunk_spec.prototype for chunk_spec in chunk_specs] + stage_specs = chunk_specs - chunk_array_batch = _as_prototype_nd_buffers(chunk_array_batch, prototypes) for aa_codec in self.array_array_codecs: - chunk_array_batch = _as_prototype_nd_buffers( - await aa_codec.encode(zip(chunk_array_batch, chunk_specs, strict=False)), - prototypes, + chunk_array_batch = await aa_codec.encode( + zip( + _as_prototype_nd_buffers(chunk_array_batch, stage_specs), + stage_specs, + strict=False, + ) ) - chunk_specs = resolve_batched(aa_codec, chunk_specs) + stage_specs = resolve_batched(aa_codec, stage_specs) - chunk_bytes_batch = _as_prototype_buffers( - await self.array_bytes_codec.encode(zip(chunk_array_batch, chunk_specs, strict=False)), - prototypes, + chunk_bytes_batch = await self.array_bytes_codec.encode( + zip(_as_prototype_nd_buffers(chunk_array_batch, stage_specs), stage_specs, strict=False) ) - chunk_specs = resolve_batched(self.array_bytes_codec, chunk_specs) + stage_specs = resolve_batched(self.array_bytes_codec, stage_specs) for bb_codec in self.bytes_bytes_codecs: - chunk_bytes_batch = _as_prototype_buffers( - await bb_codec.encode(zip(chunk_bytes_batch, chunk_specs, strict=False)), - prototypes, + chunk_bytes_batch = await bb_codec.encode( + zip( + _as_prototype_buffers(chunk_bytes_batch, stage_specs), stage_specs, strict=False + ) ) - chunk_specs = resolve_batched(bb_codec, chunk_specs) + stage_specs = resolve_batched(bb_codec, stage_specs) - return chunk_bytes_batch + return _as_prototype_buffers(chunk_bytes_batch, chunk_specs) async def encode_partial_batch( self, diff --git a/tests/test_buffer.py b/tests/test_buffer.py index 307abfe499..52146d58a9 100644 --- a/tests/test_buffer.py +++ b/tests/test_buffer.py @@ -164,17 +164,16 @@ async def test_sharding_use_of_gpu_prototype() -> None: fill_value=0, ) expect[:] = cp.arange(100).reshape(10, 10) - msg = "Creating a zarr.buffer.gpu.Buffer with an array that does not support the __cuda_array_interface__ for zero-copy transfers, falling back to slow copy based path" - with pytest.warns(ZarrUserWarning, match=msg): - await a.setitem( - selection=(slice(0, 10), slice(0, 10)), - value=expect[:], - prototype=gpu.buffer_prototype, - ) - with pytest.warns(ZarrUserWarning, match=msg): - got = await a.getitem( - selection=(slice(0, 10), slice(0, 10)), prototype=gpu.buffer_prototype - ) + # No slow-path warning: the shard index is decoded and encoded in host + # memory, and moved to the device with `from_bytes`, which does not warn. + await a.setitem( + selection=(slice(0, 10), slice(0, 10)), + value=expect[:], + prototype=gpu.buffer_prototype, + ) + got = await a.getitem( + selection=(slice(0, 10), slice(0, 10)), prototype=gpu.buffer_prototype + ) assert isinstance(got, cp.ndarray) assert cp.array_equal(expect, got) diff --git a/tests/test_codecs/test_buffer_prototype.py b/tests/test_codecs/test_buffer_prototype.py index 9daa3265c5..85894168f2 100644 --- a/tests/test_codecs/test_buffer_prototype.py +++ b/tests/test_codecs/test_buffer_prototype.py @@ -15,7 +15,7 @@ import asyncio import warnings -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from typing import TYPE_CHECKING, Any, Literal, Self import numcodecs @@ -101,6 +101,11 @@ def create_zero_length(cls) -> Self: @classmethod def from_buffer(cls, buffer: core.Buffer) -> Self: + if not isinstance(buffer, DeviceBuffer): + # As `zarr.core.buffer.gpu.Buffer.from_buffer` does, by way of its constructor. + warnings.warn( + "a buffer from host memory takes the slow path", ZarrUserWarning, stacklevel=2 + ) return cls(buffer.as_array_like()) @classmethod @@ -313,6 +318,33 @@ async def _decode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> return self._decode_sync(chunk_array, chunk_spec) +@dataclass(frozen=True) +class ExpectPrototypeBytesCodec(RecordingCodec, BytesBytesCodec): + """The bytes-to-bytes twin of `ExpectPrototypeCodec`.""" + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-expect-prototype-bytes"} + + def _check(self, chunk_bytes: Buffer, chunk_spec: ArraySpec, direction: str) -> Buffer: + self.calls.append(direction) + assert type(chunk_bytes) is chunk_spec.prototype.buffer, ( + f"expected {chunk_spec.prototype.buffer}, got {type(chunk_bytes)}" + ) + return chunk_bytes + + def _encode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return self._check(chunk_bytes, chunk_spec, "encode") + + def _decode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return self._check(chunk_bytes, chunk_spec, "decode") + + async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return self._encode_sync(chunk_bytes, chunk_spec) + + async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return self._decode_sync(chunk_bytes, chunk_spec) + + @dataclass(frozen=True) class AsyncOnlyCodec(RecordingCodec, BytesBytesCodec): """A no-op codec with only the async interface, which builds its output from `zarr.config`. @@ -401,17 +433,32 @@ def _numcodecs_chain() -> list[Codec]: def _async_only_chain() -> list[Codec]: - """The async-only codec both inside the chain and at its end.""" - return [ExpectPrototypeCodec(), BytesCodec(), AsyncOnlyCodec(), Crc32cCodec(), AsyncOnlyCodec()] + """The async-only codec at the end of the chain and inside it, each next to a checking codec.""" + return [ + ExpectPrototypeCodec(), + BytesCodec(), + AsyncOnlyCodec(), + ExpectPrototypeBytesCodec(), + AsyncOnlyCodec(), + Crc32cCodec(), + AsyncOnlyCodec(), + ] def _config_chain() -> list[Codec]: - """Codecs that ignore the prototype, both inside the chain and at each end.""" + """Codecs that ignore the prototype at each end of the chain and inside it. + + Each checking codec follows one that ignores the prototype in both + directions, so it sees that codec's output after the chain converted it. + """ return [ + ConfigArrayCodec(), ExpectPrototypeCodec(), ConfigArrayCodec(), BytesCodec(), ConfigBufferCodec(), + ExpectPrototypeBytesCodec(), + ConfigBufferCodec(), GzipCodec(), ConfigBufferCodec(), ] @@ -437,6 +484,20 @@ def _no_chain() -> list[Codec]: ), ("v2", "numcodecs-filters"), ] +# numcodecs codecs work on host memory only: on a device array (CuPy) they fail, +# with or without this module's conversions. The fake device array is a NumPy +# array underneath, so it would let them pass; these run with a host prototype only. +HOST_ONLY_CHAINS = ("numcodecs", "numcodecs-filters") + + +def _cases(directions: Iterable[Direction], layout_chains: Iterable[tuple[str, str]]) -> list[Any]: + """The (direction, layout, chain) cases where the chain can run on the direction's prototype.""" + return [ + pytest.param(direction, layout, chain, id=f"{layout}-{chain}-{direction.name}") + for direction in directions + for layout, chain in layout_chains + if chain not in HOST_ONLY_CHAINS or direction.prototype is cpu.buffer_prototype + ] def _chain_kwargs(chain: list[Codec]) -> dict[str, Any]: @@ -503,8 +564,7 @@ def _host(array: Any) -> npt.NDArray[Any]: @pytest.mark.parametrize("pipeline", PIPELINES) -@pytest.mark.parametrize("direction", DIRECTIONS, ids=lambda d: d.name) -@pytest.mark.parametrize(("layout", "chain"), LAYOUT_CHAINS) +@pytest.mark.parametrize(("direction", "layout", "chain"), _cases(DIRECTIONS, LAYOUT_CHAINS)) def test_codecs_use_the_given_prototype( pipeline: str, direction: Direction, layout: Layout, chain: str ) -> None: @@ -528,9 +588,18 @@ def test_codecs_use_the_given_prototype( assert {"encode", "decode"} <= set(codec.calls), codec -@pytest.mark.parametrize("direction", DIRECTIONS, ids=lambda d: d.name) +@pytest.mark.parametrize( + "direction", + [d for d in DIRECTIONS if d.prototype is cpu.buffer_prototype], + ids=lambda d: d.name, +) def test_v2_codec_decodes_into_the_given_prototype(direction: Direction) -> None: - """`V2Codec` returns the spec's prototype's array kind, not the configured one.""" + """`V2Codec` returns the spec's prototype's array kind, not the configured one. + + The pipeline copies a decoded chunk into an output buffer of the call's kind, + so an array read alone would not show a decoded chunk of the wrong kind. + `V2Codec` runs numcodecs, which works on host memory only. + """ zdtype = get_data_type_from_native_dtype(np.dtype("int32")) spec = ArraySpec( shape=(2, 2), @@ -550,36 +619,38 @@ def test_v2_codec_decodes_into_the_given_prototype(direction: Direction) -> None np.testing.assert_array_equal(decoded.as_numpy_array(), data) -# Chains whose codecs all follow the prototype: the ones that may run with no usable config. -PROTOTYPE_CHAINS = ("zarr", "numcodecs") +# `zarr.config` names a buffer kind that cannot be built. +UNUSABLE_CONFIG_DIRECTIONS = ( + Direction("config-unusable-call-host", cpu.buffer_prototype, UNUSABLE_CONFIG, np.ndarray), + Direction("config-unusable-call-device", DEVICE_PROTOTYPE, UNUSABLE_CONFIG, DeviceArray), +) +# Chains whose codecs all follow the prototype; the others read `zarr.config` by design. +PROTOTYPE_LAYOUT_CHAINS = [ + (layout, chain) + for layout, chain in LAYOUT_CHAINS + if chain in ("zarr", "numcodecs", "numcodecs-filters") +] @pytest.mark.parametrize("pipeline", PIPELINES) @pytest.mark.parametrize( - "prototype", [cpu.buffer_prototype, DEVICE_PROTOTYPE], ids=["host", "device"] -) -@pytest.mark.parametrize( - ("layout", "chain"), - [ - (layout, chain) - for layout, chain in LAYOUT_CHAINS - if chain in (*PROTOTYPE_CHAINS, "numcodecs-filters") - ], + ("direction", "layout", "chain"), _cases(UNUSABLE_CONFIG_DIRECTIONS, PROTOTYPE_LAYOUT_CHAINS) ) def test_codecs_read_no_buffer_config( - pipeline: str, prototype: BufferPrototype, layout: Layout, chain: str + pipeline: str, direction: Direction, layout: Layout, chain: str ) -> None: - """With a prototype given and codecs that follow it, no buffer is built from `zarr.config`. - - `zarr.config` names a buffer kind that cannot be built; reads and writes still work. - """ + """With a prototype given and codecs that follow it, no buffer is built from `zarr.config`.""" codecs = _no_chain() if layout == "v2" else CHAINS[chain]() + store = RecordingStore() + # The array's metadata is written with the configured kind, so create it first. with config.set({"codec_pipeline.path": pipeline}): - array = _create(RecordingStore(), layout, codecs) - with config.set({**UNUSABLE_CONFIG, "codec_pipeline.path": pipeline}): - results = asyncio.run(_round_trip(array, prototype)) + array = _create(store, layout, codecs) + with config.set({**direction.buffer_config, "codec_pipeline.path": pipeline}): + results = asyncio.run(_round_trip(array, direction.prototype)) for got, expected in results: + assert type(got) is direction.array_type np.testing.assert_array_equal(_host(got), expected) + assert store.chunk_value_types == {direction.prototype.buffer} def _other_kind(prototype: BufferPrototype) -> BufferPrototype: @@ -598,9 +669,12 @@ def _int32_spec(prototype: BufferPrototype) -> ArraySpec: async def _run_chain( - runner: str, direction: Literal["encode", "decode"], chunk: Any, spec: ArraySpec + runner: str, + direction: Literal["encode", "decode"], + chunk: Any, + spec: ArraySpec, + codecs: tuple[Codec, ...] = (BytesCodec(),), ) -> Any: - codecs = (BytesCodec(),) if runner == "chunk-transform": transform = ChunkTransform(codecs=codecs) if direction == "encode": @@ -617,7 +691,10 @@ async def _run_chain( return next(iter(await pipeline.decode([(chunk, spec)]))) -@pytest.mark.parametrize("runner", ["chunk-transform", "async-chunk-transform", "batched-pipeline"]) +RUNNERS = ["chunk-transform", "async-chunk-transform", "batched-pipeline"] + + +@pytest.mark.parametrize("runner", RUNNERS) @pytest.mark.parametrize( "prototype", [cpu.buffer_prototype, DEVICE_PROTOTYPE], ids=["host", "device"] ) @@ -659,3 +736,159 @@ def test_scatter_chunk_converts_a_chunk_of_another_kind(prototype: BufferPrototy chunk, out, chunk_spec=spec, out_selection=(slice(None), slice(None)), drop_axes=() ) np.testing.assert_array_equal(out.as_numpy_array(), data) + + +@dataclass(frozen=True) +class SwitchPrototypeCodec(ArrayArrayCodec): + """A no-op codec that names another prototype for the codecs after it.""" + + target: BufferPrototype + is_fixed_size = True + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-switch-prototype"} + + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: + return input_byte_length + + def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec: + return replace(chunk_spec, prototype=self.target) + + def _encode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + assert type(chunk_array) is chunk_spec.prototype.nd_buffer + return chunk_array + + def _decode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + assert type(chunk_array) is chunk_spec.prototype.nd_buffer + return chunk_array + + async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._encode_sync(chunk_array, chunk_spec) + + async def _decode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._decode_sync(chunk_array, chunk_spec) + + +@pytest.mark.parametrize("runner", RUNNERS) +@pytest.mark.parametrize( + "prototype", [cpu.buffer_prototype, DEVICE_PROTOTYPE], ids=["host", "device"] +) +def test_codec_chains_give_each_codec_its_own_specs_kind( + runner: str, prototype: BufferPrototype +) -> None: + """A codec gets the kind its own spec names; the chain returns the kind the caller's spec names. + + `SwitchPrototypeCodec` names the other kind for the codecs after it, which + `ExpectPrototypeCodec` checks. `ConfigArrayCodec`, first in the chain, returns + the configured (host) kind from the decode, which the chain converts. + """ + spec = _int32_spec(prototype) + expect = ExpectPrototypeCodec() + expect_bytes = ExpectPrototypeBytesCodec() + codecs = ( + ConfigArrayCodec(), + SwitchPrototypeCodec(target=_other_kind(prototype)), + expect, + BytesCodec(), + expect_bytes, + ) + data = np.arange(4, dtype="int32").reshape(2, 2) + chunk = prototype.nd_buffer.from_numpy_array(data) + encoded = asyncio.run(_run_chain(runner, "encode", chunk, spec, codecs)) + assert type(encoded) is prototype.buffer + decoded = asyncio.run(_run_chain(runner, "decode", encoded, spec, codecs)) + assert type(decoded) is prototype.nd_buffer + np.testing.assert_array_equal(decoded.as_numpy_array(), data) + assert {"encode", "decode"} <= set(expect.calls) + assert {"encode", "decode"} <= set(expect_bytes.calls) + + +@dataclass(frozen=True) +class RawFilterCodec(ArrayArrayCodec): + """A no-op codec whose decode returns a NumPy array, not an `NDBuffer`.""" + + is_fixed_size = True + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-raw-filter"} + + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: + return input_byte_length + + async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return chunk_array + + async def _decode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return np.asarray(chunk_array) + + +@dataclass(frozen=True) +class RawSerializerCodec(ArrayBytesCodec): + """A codec whose decode takes `bytes` or a `Buffer` and returns a NumPy array.""" + + is_fixed_size = True + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-raw-serializer"} + + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: + return input_byte_length + + async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer: + return chunk_spec.prototype.buffer.from_bytes(chunk_array.as_numpy_array().tobytes()) + + async def _decode_single(self, chunk_bytes: Any, chunk_spec: ArraySpec) -> Any: + raw = chunk_bytes if isinstance(chunk_bytes, bytes) else chunk_bytes.to_bytes() + dtype = chunk_spec.dtype.to_native_dtype() + return np.frombuffer(raw, dtype=dtype).reshape(chunk_spec.shape) + + +@dataclass(frozen=True) +class RawBytesCodec(BytesBytesCodec): + """A no-op codec whose decode returns `bytes`, not a `Buffer`.""" + + is_fixed_size = True + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-raw-bytes"} + + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: + return input_byte_length + + async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return chunk_bytes + + async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Any: + return chunk_bytes.to_bytes() + + +@pytest.mark.parametrize("pipeline", PIPELINES) +@pytest.mark.parametrize("sharded", [False, True], ids=["v3", "v3-sharded"]) +def test_codecs_that_return_raw_arrays_and_bytes_keep_working(pipeline: str, sharded: bool) -> None: + """Decoded values that are not `Buffer`/`NDBuffer` pass through the chain unchanged. + + The codec contract asks for `Buffer`/`NDBuffer`, but codecs outside zarr + whose decode returns a NumPy array or `bytes` could be written and read + before the pipelines converted buffers, and still can. (A partial write + through them failed before and still does: it merges into the raw array.) + """ + codecs: list[Codec] = [RawFilterCodec(), RawSerializerCodec(), RawBytesCodec()] + common: dict[str, Any] = {"shape": (8, 8), "dtype": "int32", "fill_value": 0} + with config.set({"codec_pipeline.path": pipeline}): + if sharded: + array = zarr.create_array( + MemoryStore(), + chunks=(4, 4), + serializer=ShardingCodec(chunk_shape=(2, 2), codecs=codecs), + compressors=None, + **common, + ) + else: + array = zarr.create_array( + MemoryStore(), chunks=(2, 2), **_chain_kwargs(codecs), **common + ) + expected = np.arange(64, dtype="int32").reshape(8, 8) + array[:] = expected + full, part = array[:], array[1:6, 2:7] + np.testing.assert_array_equal(full, expected) + np.testing.assert_array_equal(part, expected[1:6, 2:7]) From fee21bfe12286b0ad3bc122758348d8fe6160900 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 12:57:58 +0100 Subject: [PATCH 4/7] docs: add changelog fragment for #474 Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- changes/474.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changes/474.bugfix.md diff --git a/changes/474.bugfix.md b/changes/474.bugfix.md new file mode 100644 index 0000000000..74d7483be8 --- /dev/null +++ b/changes/474.bugfix.md @@ -0,0 +1 @@ +Reading or writing a sharded array with a buffer prototype other than the one `zarr.config` names no longer fails, and a Zarr format 2 array decodes into the requested prototype's buffer kind. The codec pipelines now hand each codec its input in the buffer kind its chunk spec names and convert a `Buffer` or `NDBuffer` of another kind that a codec returns, so codecs that build their buffers from `zarr.config` keep working. From 5735fba0d1701b021b3704f96d3084357ec6ed97 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 13:19:40 +0100 Subject: [PATCH 5/7] fix(codecs): type the buffer conversion helpers and fix stale docstrings Round-3 review fixes: - `_as_prototype_buffer`/`_as_prototype_nd_buffer` have `Buffer -> Buffer` / `None -> None` overloads instead of `T -> T`, so passing the wrong kind of value is a type error and the declared return type is the real one. - The `ChunkTransform` and `AsyncChunkTransform` docstrings and the extending guide describe per-stage conversion and when it copies. - The raw-value test codecs are sync-capable, so the sync chain runner is run with raw values too; the `V2Codec` unit test runs on every direction, with no numcodecs filters (numcodecs runs on host memory only). Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- docs/user-guide/extending.md | 2 +- src/zarr/core/buffer/core.py | 38 ++++++++++------- src/zarr/core/chunk_utils.py | 7 ++-- src/zarr/core/codec_pipeline.py | 5 ++- tests/test_codecs/test_buffer_prototype.py | 47 ++++++++++++++-------- 5 files changed, 63 insertions(+), 36 deletions(-) diff --git a/docs/user-guide/extending.md b/docs/user-guide/extending.md index 0867c432e2..89a230ee35 100644 --- a/docs/user-guide/extending.md +++ b/docs/user-guide/extending.md @@ -54,7 +54,7 @@ A codec receives the chunk's buffer kind (host or GPU memory, for instance) in [`zarr.config`][]: a read or write may ask for a different kind than the one configured. The codec pipelines hand each codec its input as the kind its `chunk_spec.prototype` names, and convert a `Buffer` or `NDBuffer` of another kind that a codec returns, -at the cost of a copy. A cross-kind `NDBuffer` conversion goes through +which copies the data when it has to move between host and device memory. A cross-kind `NDBuffer` conversion goes through `as_numpy_array` and `from_numpy_array`, so a custom array buffer class must support both. Codecs should return `Buffer` and `NDBuffer` instances; any other value is passed on unchanged. diff --git a/src/zarr/core/buffer/core.py b/src/zarr/core/buffer/core.py index ec6dde86d8..cb58a93c51 100644 --- a/src/zarr/core/buffer/core.py +++ b/src/zarr/core/buffer/core.py @@ -11,6 +11,7 @@ Protocol, SupportsIndex, cast, + overload, runtime_checkable, ) @@ -598,7 +599,11 @@ class BufferPrototype(NamedTuple): nd_buffer: type[NDBuffer] -def _as_prototype_buffer[T](value: T, prototype: BufferPrototype) -> T: +@overload +def _as_prototype_buffer(value: Buffer, prototype: BufferPrototype) -> Buffer: ... +@overload +def _as_prototype_buffer(value: None, prototype: BufferPrototype) -> None: ... +def _as_prototype_buffer(value: Buffer | None, prototype: BufferPrototype) -> Buffer | None: """Return a `Buffer` of another kind as a `prototype.buffer`; return anything else unchanged. The codec pipelines pass each codec's input, and the chain's output, through @@ -609,16 +614,21 @@ def _as_prototype_buffer[T](value: T, prototype: BufferPrototype) -> T: as `bytes` from a codec that predates the `Buffer` contract, is passed on unchanged, as it was before these conversions existed. """ - if isinstance(value, Buffer) and not isinstance(value, prototype.buffer): - # Through host memory with `from_bytes`, not `from_buffer`: the GPU - # buffer's `from_buffer` warns about a slow path when given host memory, - # and a host buffer's `as_buffer_like` is a view, so host kinds convert - # without a copy. - return cast("T", prototype.buffer.from_bytes(value.as_buffer_like())) - return value - - -def _as_prototype_nd_buffer[T](value: T, prototype: BufferPrototype) -> T: + if not isinstance(value, Buffer) or isinstance(value, prototype.buffer): + return value + # Through host memory with `from_bytes`, not `from_buffer`: between host kinds + # this copies nothing (`as_buffer_like` is a view of host data), and a GPU + # kind's `from_bytes` copies to the device without the slow-path warning its + # `from_buffer` gives for host memory. Between two device kinds it copies + # through the host, which only a codec that ignores the prototype causes. + return prototype.buffer.from_bytes(value.as_buffer_like()) + + +@overload +def _as_prototype_nd_buffer(value: NDBuffer, prototype: BufferPrototype) -> NDBuffer: ... +@overload +def _as_prototype_nd_buffer(value: None, prototype: BufferPrototype) -> None: ... +def _as_prototype_nd_buffer(value: NDBuffer | None, prototype: BufferPrototype) -> NDBuffer | None: """Return an `NDBuffer` of another kind as a `prototype.nd_buffer`; return anything else unchanged. `NDBuffer` has no `from_buffer`; the conversion goes through a NumPy array in @@ -626,9 +636,9 @@ def _as_prototype_nd_buffer[T](value: T, prototype: BufferPrototype) -> T: from a codec that predates the `NDBuffer` contract, is passed on unchanged. See `_as_prototype_buffer`. """ - if isinstance(value, NDBuffer) and not isinstance(value, prototype.nd_buffer): - return cast("T", prototype.nd_buffer.from_numpy_array(value.as_numpy_array())) - return value + if not isinstance(value, NDBuffer) or isinstance(value, prototype.nd_buffer): + return value + return prototype.nd_buffer.from_numpy_array(value.as_numpy_array()) # The default buffer prototype used throughout the Zarr codebase. diff --git a/src/zarr/core/chunk_utils.py b/src/zarr/core/chunk_utils.py index 89411addb1..bbd2ea7ac9 100644 --- a/src/zarr/core/chunk_utils.py +++ b/src/zarr/core/chunk_utils.py @@ -230,9 +230,10 @@ class ChunkTransform: All codecs must implement `SupportsSyncCodec`. Construction will raise `TypeError` if any codec does not. - Every codec gets its input, and every codec's output is passed on, as the - buffer kind `chunk_spec.prototype` names (see `_as_prototype_buffer`), so a - codec that ignores the prototype cannot mix buffer kinds in the chain. + Every codec gets its input as the buffer kind its own spec's prototype + names, and the chain's output is returned as the kind `chunk_spec.prototype` + names (see `_as_prototype_buffer`), so a codec that ignores the prototype + cannot mix buffer kinds in the chain. """ codecs: tuple[Codec, ...] diff --git a/src/zarr/core/codec_pipeline.py b/src/zarr/core/codec_pipeline.py index f3f3c490c7..32020adbe7 100644 --- a/src/zarr/core/codec_pipeline.py +++ b/src/zarr/core/codec_pipeline.py @@ -542,8 +542,9 @@ class AsyncChunkTransform: correctly-evolved per-stage spec (via the shared `resolve_aa_specs`). Unlike ChunkTransform it places no `SupportsSyncCodec` requirement on the - codecs, so it works for async-only codecs. Like ChunkTransform it passes - every codec's input and output as the kind `chunk_spec.prototype` names. Unlike the batched codec API it + codecs, so it works for async-only codecs. Like ChunkTransform it gives + every codec its input as the kind its own spec names, and returns the + chain's output as the kind `chunk_spec.prototype` names. Unlike the batched codec API it operates on one chunk at a time — the mini-batch fan-out is a BatchedCodecPipeline concern and deliberately not reintroduced here. """ diff --git a/tests/test_codecs/test_buffer_prototype.py b/tests/test_codecs/test_buffer_prototype.py index 85894168f2..5ba3db5c89 100644 --- a/tests/test_codecs/test_buffer_prototype.py +++ b/tests/test_codecs/test_buffer_prototype.py @@ -101,7 +101,7 @@ def create_zero_length(cls) -> Self: @classmethod def from_buffer(cls, buffer: core.Buffer) -> Self: - if not isinstance(buffer, DeviceBuffer): + if not isinstance(buffer.as_array_like(), DeviceArray): # As `zarr.core.buffer.gpu.Buffer.from_buffer` does, by way of its constructor. warnings.warn( "a buffer from host memory takes the slow path", ZarrUserWarning, stacklevel=2 @@ -118,7 +118,7 @@ def as_numpy_array(self) -> npt.NDArray[Any]: def combine(self, others: Iterable[core.Buffer]) -> Self: data: list[Any] = [self._data] for other in others: - if not isinstance(other, DeviceBuffer): + if not isinstance(other.as_array_like(), DeviceArray): # As `zarr.core.buffer.gpu.Buffer.combine` does, by way of its constructor. warnings.warn( "combining host memory takes the slow path", ZarrUserWarning, stacklevel=2 @@ -588,17 +588,14 @@ def test_codecs_use_the_given_prototype( assert {"encode", "decode"} <= set(codec.calls), codec -@pytest.mark.parametrize( - "direction", - [d for d in DIRECTIONS if d.prototype is cpu.buffer_prototype], - ids=lambda d: d.name, -) +@pytest.mark.parametrize("direction", DIRECTIONS, ids=lambda d: d.name) def test_v2_codec_decodes_into_the_given_prototype(direction: Direction) -> None: """`V2Codec` returns the spec's prototype's array kind, not the configured one. The pipeline copies a decoded chunk into an output buffer of the call's kind, - so an array read alone would not show a decoded chunk of the wrong kind. - `V2Codec` runs numcodecs, which works on host memory only. + so an array read alone would not show a decoded chunk of the wrong kind. No + filters or compressor: numcodecs runs on host memory only, and a GPU v2 array + without them is a real case. """ zdtype = get_data_type_from_native_dtype(np.dtype("int32")) spec = ArraySpec( @@ -608,7 +605,7 @@ def test_v2_codec_decodes_into_the_given_prototype(direction: Direction) -> None config=ArrayConfig.from_dict({}), prototype=direction.prototype, ) - codec = V2Codec(filters=(numcodecs.Delta(dtype=" dict[str, Any]: def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: return input_byte_length - async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + def _encode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: return chunk_array - async def _decode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + def _decode_sync(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: return np.asarray(chunk_array) + async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return self._encode_sync(chunk_array, chunk_spec) + + async def _decode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return self._decode_sync(chunk_array, chunk_spec) + @dataclass(frozen=True) class RawSerializerCodec(ArrayBytesCodec): @@ -834,14 +837,20 @@ def to_dict(self) -> dict[str, Any]: def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: return input_byte_length - async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer: + def _encode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer: return chunk_spec.prototype.buffer.from_bytes(chunk_array.as_numpy_array().tobytes()) - async def _decode_single(self, chunk_bytes: Any, chunk_spec: ArraySpec) -> Any: + def _decode_sync(self, chunk_bytes: Any, chunk_spec: ArraySpec) -> Any: raw = chunk_bytes if isinstance(chunk_bytes, bytes) else chunk_bytes.to_bytes() dtype = chunk_spec.dtype.to_native_dtype() return np.frombuffer(raw, dtype=dtype).reshape(chunk_spec.shape) + async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer: + return self._encode_sync(chunk_array, chunk_spec) + + async def _decode_single(self, chunk_bytes: Any, chunk_spec: ArraySpec) -> Any: + return self._decode_sync(chunk_bytes, chunk_spec) + @dataclass(frozen=True) class RawBytesCodec(BytesBytesCodec): @@ -855,12 +864,18 @@ def to_dict(self) -> dict[str, Any]: def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: return input_byte_length - async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + def _encode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: return chunk_bytes - async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Any: + def _decode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Any: return chunk_bytes.to_bytes() + async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return self._encode_sync(chunk_bytes, chunk_spec) + + async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Any: + return self._decode_sync(chunk_bytes, chunk_spec) + @pytest.mark.parametrize("pipeline", PIPELINES) @pytest.mark.parametrize("sharded", [False, True], ids=["v3", "v3-sharded"]) From 19c0986fd3beddb850a2e9060682575792a18e5f Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 13:26:40 +0100 Subject: [PATCH 6/7] test(codecs): run raw-value codecs through both chain runners The raw-value test codecs became sync-capable in the previous commit, which moved the fused pipeline from the async chain runner to the sync one instead of adding it. Parametrize over sync-capable and async-only variants so both runners see raw values. Also rewrap the extending-guide paragraph. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- docs/user-guide/extending.md | 5 +- tests/test_codecs/test_buffer_prototype.py | 82 ++++++++++++++++------ 2 files changed, 65 insertions(+), 22 deletions(-) diff --git a/docs/user-guide/extending.md b/docs/user-guide/extending.md index 89a230ee35..340e48772e 100644 --- a/docs/user-guide/extending.md +++ b/docs/user-guide/extending.md @@ -54,8 +54,9 @@ A codec receives the chunk's buffer kind (host or GPU memory, for instance) in [`zarr.config`][]: a read or write may ask for a different kind than the one configured. The codec pipelines hand each codec its input as the kind its `chunk_spec.prototype` names, and convert a `Buffer` or `NDBuffer` of another kind that a codec returns, -which copies the data when it has to move between host and device memory. A cross-kind `NDBuffer` conversion goes through -`as_numpy_array` and `from_numpy_array`, so a custom array buffer class must support both. +which copies the data when it moves between host and device memory. A cross-kind +`NDBuffer` conversion goes through `as_numpy_array` and `from_numpy_array`, so a +custom array buffer class must support both. Codecs should return `Buffer` and `NDBuffer` instances; any other value is passed on unchanged. diff --git a/tests/test_codecs/test_buffer_prototype.py b/tests/test_codecs/test_buffer_prototype.py index 5ba3db5c89..234e0a0d10 100644 --- a/tests/test_codecs/test_buffer_prototype.py +++ b/tests/test_codecs/test_buffer_prototype.py @@ -801,8 +801,8 @@ def test_codec_chains_give_each_codec_its_own_specs_kind( @dataclass(frozen=True) -class RawFilterCodec(ArrayArrayCodec): - """A no-op codec whose decode returns a NumPy array, not an `NDBuffer`.""" +class AsyncOnlyRawFilterCodec(ArrayArrayCodec): + """A no-op codec whose decode returns a NumPy array, not an `NDBuffer`; async interface only.""" is_fixed_size = True @@ -812,22 +812,22 @@ def to_dict(self) -> dict[str, Any]: def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: return input_byte_length - def _encode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + def _encode_raw(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: return chunk_array - def _decode_sync(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + def _decode_raw(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: return np.asarray(chunk_array) async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: - return self._encode_sync(chunk_array, chunk_spec) + return self._encode_raw(chunk_array, chunk_spec) async def _decode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: - return self._decode_sync(chunk_array, chunk_spec) + return self._decode_raw(chunk_array, chunk_spec) @dataclass(frozen=True) -class RawSerializerCodec(ArrayBytesCodec): - """A codec whose decode takes `bytes` or a `Buffer` and returns a NumPy array.""" +class AsyncOnlyRawSerializerCodec(ArrayBytesCodec): + """A codec whose decode takes `bytes` or a `Buffer` and returns a NumPy array; async only.""" is_fixed_size = True @@ -837,24 +837,24 @@ def to_dict(self) -> dict[str, Any]: def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: return input_byte_length - def _encode_sync(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer: + def _encode_raw(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer: return chunk_spec.prototype.buffer.from_bytes(chunk_array.as_numpy_array().tobytes()) - def _decode_sync(self, chunk_bytes: Any, chunk_spec: ArraySpec) -> Any: + def _decode_raw(self, chunk_bytes: Any, chunk_spec: ArraySpec) -> Any: raw = chunk_bytes if isinstance(chunk_bytes, bytes) else chunk_bytes.to_bytes() dtype = chunk_spec.dtype.to_native_dtype() return np.frombuffer(raw, dtype=dtype).reshape(chunk_spec.shape) async def _encode_single(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer: - return self._encode_sync(chunk_array, chunk_spec) + return self._encode_raw(chunk_array, chunk_spec) async def _decode_single(self, chunk_bytes: Any, chunk_spec: ArraySpec) -> Any: - return self._decode_sync(chunk_bytes, chunk_spec) + return self._decode_raw(chunk_bytes, chunk_spec) @dataclass(frozen=True) -class RawBytesCodec(BytesBytesCodec): - """A no-op codec whose decode returns `bytes`, not a `Buffer`.""" +class AsyncOnlyRawBytesCodec(BytesBytesCodec): + """A no-op codec whose decode returns `bytes`, not a `Buffer`; async interface only.""" is_fixed_size = True @@ -864,30 +864,72 @@ def to_dict(self) -> dict[str, Any]: def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: return input_byte_length - def _encode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + def _encode_raw(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: return chunk_bytes - def _decode_sync(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Any: + def _decode_raw(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Any: return chunk_bytes.to_bytes() async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: - return self._encode_sync(chunk_bytes, chunk_spec) + return self._encode_raw(chunk_bytes, chunk_spec) async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Any: - return self._decode_sync(chunk_bytes, chunk_spec) + return self._decode_raw(chunk_bytes, chunk_spec) + + +@dataclass(frozen=True) +class RawFilterCodec(AsyncOnlyRawFilterCodec): + """`AsyncOnlyRawFilterCodec` with the sync interface too.""" + + def _encode_sync(self, chunk: Any, chunk_spec: ArraySpec) -> Any: + return self._encode_raw(chunk, chunk_spec) + + def _decode_sync(self, chunk: Any, chunk_spec: ArraySpec) -> Any: + return self._decode_raw(chunk, chunk_spec) + + +@dataclass(frozen=True) +class RawSerializerCodec(AsyncOnlyRawSerializerCodec): + """`AsyncOnlyRawSerializerCodec` with the sync interface too.""" + + def _encode_sync(self, chunk: Any, chunk_spec: ArraySpec) -> Any: + return self._encode_raw(chunk, chunk_spec) + + def _decode_sync(self, chunk: Any, chunk_spec: ArraySpec) -> Any: + return self._decode_raw(chunk, chunk_spec) + + +@dataclass(frozen=True) +class RawBytesCodec(AsyncOnlyRawBytesCodec): + """`AsyncOnlyRawBytesCodec` with the sync interface too.""" + + def _encode_sync(self, chunk: Any, chunk_spec: ArraySpec) -> Any: + return self._encode_raw(chunk, chunk_spec) + + def _decode_sync(self, chunk: Any, chunk_spec: ArraySpec) -> Any: + return self._decode_raw(chunk, chunk_spec) @pytest.mark.parametrize("pipeline", PIPELINES) @pytest.mark.parametrize("sharded", [False, True], ids=["v3", "v3-sharded"]) -def test_codecs_that_return_raw_arrays_and_bytes_keep_working(pipeline: str, sharded: bool) -> None: +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async-only"]) +def test_codecs_that_return_raw_arrays_and_bytes_keep_working( + pipeline: str, sharded: bool, sync: bool +) -> None: """Decoded values that are not `Buffer`/`NDBuffer` pass through the chain unchanged. The codec contract asks for `Buffer`/`NDBuffer`, but codecs outside zarr whose decode returns a NumPy array or `bytes` could be written and read before the pipelines converted buffers, and still can. (A partial write through them failed before and still does: it merges into the raw array.) + The sync-capable codecs run through the sync chain runner in the fused + pipeline; the async-only ones through the async runner. """ - codecs: list[Codec] = [RawFilterCodec(), RawSerializerCodec(), RawBytesCodec()] + codecs: list[Codec] = ( + [RawFilterCodec(), RawSerializerCodec(), RawBytesCodec()] + if sync + else [AsyncOnlyRawFilterCodec(), AsyncOnlyRawSerializerCodec(), AsyncOnlyRawBytesCodec()] + ) common: dict[str, Any] = {"shape": (8, 8), "dtype": "int32", "fill_value": 0} with config.set({"codec_pipeline.path": pipeline}): if sharded: From e858d178b1ffb88a6408870a876c10ecfd687afc Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Mon, 30 Nov 2026 13:39:40 +0100 Subject: [PATCH 7/7] test(codecs): use the native int32 dtype for the Delta filter in the prototype tests On the big-endian s390x runner, `Delta(dtype=" --- tests/test_codecs/test_buffer_prototype.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_codecs/test_buffer_prototype.py b/tests/test_codecs/test_buffer_prototype.py index 234e0a0d10..a2c84cca4c 100644 --- a/tests/test_codecs/test_buffer_prototype.py +++ b/tests/test_codecs/test_buffer_prototype.py @@ -425,7 +425,7 @@ def _zarr_chain() -> list[Codec]: def _numcodecs_chain() -> list[Codec]: return [ ExpectPrototypeCodec(), - zarr_numcodecs.Delta(dtype="