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. diff --git a/docs/user-guide/extending.md b/docs/user-guide/extending.md index bf0eb442c9..340e48772e 100644 --- a/docs/user-guide/extending.md +++ b/docs/user-guide/extending.md @@ -48,6 +48,18 @@ 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, +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. + 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/_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..9ed4cf8319 100644 --- a/src/zarr/codecs/sharding.py +++ b/src/zarr/codecs/sharding.py @@ -33,9 +33,9 @@ Buffer, BufferPrototype, NDBuffer, - default_buffer_prototype, 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, @@ -73,7 +73,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 @@ -153,6 +153,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 @@ -161,11 +165,6 @@ 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 @@ -344,10 +343,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 +652,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( @@ -706,7 +705,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 +840,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 +942,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 +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`). + index_bytes = _as_prototype_buffer(index_bytes, buffer_prototype) if self.index_location == "start": buffers.insert(0, index_bytes) else: @@ -1410,7 +1411,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 +1435,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 +1457,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: @@ -1602,7 +1603,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 +1650,12 @@ 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`). 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(), ) def _get_chunk_spec(self, shard_spec: ArraySpec) -> ArraySpec: diff --git a/src/zarr/core/buffer/core.py b/src/zarr/core/buffer/core.py index d2cd4a795b..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,6 +599,48 @@ class BufferPrototype(NamedTuple): nd_buffer: type[NDBuffer] +@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 + 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. 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 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 + 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 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. 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..bbd2ea7ac9 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,11 @@ class ChunkTransform: All codecs must implement `SupportsSyncCodec`. Construction will raise `TypeError` if any codec does not. + + 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, ...] @@ -316,16 +325,20 @@ def decode_chunk(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBuffer: """ aa_specs, ab_spec = self._resolve_specs(chunk_spec) - data: Buffer = chunk_bytes + data = chunk_bytes for bb_codec in reversed(self._bb_codecs): - data = bb_codec._decode_sync(data, ab_spec) + data = bb_codec._decode_sync(_as_prototype_buffer(data, ab_spec.prototype), ab_spec) - chunk_array: NDBuffer = self._ab_codec._decode_sync(data, ab_spec) + 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 = aa_codec._decode_sync(chunk_array, aa_spec) + 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. @@ -342,25 +355,31 @@ def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Buffer | """ aa_specs, ab_spec = self._resolve_specs(chunk_spec) - aa_data: NDBuffer = chunk_array + 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 = 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: Buffer = ab_result + 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 = 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 dd893ea8d8..32020adbe7 100644 --- a/src/zarr/core/codec_pipeline.py +++ b/src/zarr/core/codec_pipeline.py @@ -19,13 +19,14 @@ 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, + fill_value_or_default, # noqa: F401 # still importable from this module merge_and_encode_chunk, scatter_chunk, ) @@ -128,6 +129,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], specs: Iterable[ArraySpec] +) -> list[Buffer | None]: + """`_as_prototype_buffer` over a batch of chunks, each to its spec's prototype.""" + return [ + _as_prototype_buffer(chunk, spec.prototype) + for chunk, spec in zip(chunks, specs, strict=True) + ] + + +def _as_prototype_nd_buffers( + chunks: Iterable[NDBuffer | None], specs: Iterable[ArraySpec] +) -> list[NDBuffer | None]: + """`_as_prototype_nd_buffer` over a batch of chunks, each to its spec's prototype.""" + return [ + _as_prototype_nd_buffer(chunk, spec.prototype) + for chunk, spec in zip(chunks, specs, 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 +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. 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. """ @@ -546,16 +569,22 @@ async def decode_chunk(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> NDBu """Decode one chunk through the chain (bb -> ab -> aa), async.""" aa_specs, ab_spec = resolve_aa_specs(self._aa_codecs, chunk_spec) - data: Buffer = chunk_bytes + data = chunk_bytes for bb_codec in reversed(self._bb_codecs): - data = await bb_codec._decode_single(data, ab_spec) + data = await bb_codec._decode_single( + _as_prototype_buffer(data, ab_spec.prototype), ab_spec + ) - chunk_array: NDBuffer = await self._ab_codec._decode_single(data, ab_spec) + 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 = await aa_codec._decode_single(chunk_array, aa_spec) + 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. @@ -565,25 +594,31 @@ async def encode_chunk(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> Bu """ aa_specs, ab_spec = resolve_aa_specs(self._aa_codecs, chunk_spec) - aa_data: NDBuffer = chunk_array + 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 = 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: Buffer = ab_result + 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 = bb_result - return bb_data + return _as_prototype_buffer(bb_data, chunk_spec.prototype) @dataclass(frozen=True) @@ -696,6 +731,9 @@ async def decode_batch( self, chunk_bytes_and_specs: Iterable[tuple[Buffer | None, ArraySpec]], ) -> Iterable[NDBuffer | None]: + # 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) ( @@ -706,20 +744,32 @@ async def decode_batch( 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) + 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 = await ab_codec.decode( - zip(chunk_bytes_batch, chunk_spec_batch, strict=False) + 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 = await aa_codec.decode( - zip(chunk_array_batch, chunk_spec_batch, strict=False) + 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, @@ -736,28 +786,39 @@ async def encode_batch( self, chunk_arrays_and_specs: Iterable[tuple[NDBuffer | None, ArraySpec]], ) -> Iterable[Buffer | None]: + # 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) + stage_specs = chunk_specs for aa_codec in self.array_array_codecs: chunk_array_batch = await aa_codec.encode( - zip(chunk_array_batch, chunk_specs, strict=False) + 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 = await self.array_bytes_codec.encode( - zip(chunk_array_batch, chunk_specs, strict=False) + 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 = await bb_codec.encode( - zip(chunk_bytes_batch, chunk_specs, strict=False) + 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, @@ -788,14 +849,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 +1398,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_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 new file mode 100644 index 0000000000..a2c84cca4c --- /dev/null +++ b/tests/test_codecs/test_buffer_prototype.py @@ -0,0 +1,951 @@ +"""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 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, replace +from typing import TYPE_CHECKING, Any, Literal, Self + +import numcodecs +import numpy as np +import numpy.typing as npt +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, 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 + +if TYPE_CHECKING: + from collections.abc import Iterable + + from zarr.abc.codec import Codec + + +# --- 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: + 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 + ) + 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.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 + ) + 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), +} + + +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 the buffer kind `zarr.config` names.""" + + name: str + prototype: BufferPrototype + buffer_config: dict[str, str] + array_type: type[np.ndarray[Any, Any]] + + +DIRECTIONS = ( + 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", +) + + +# --- codecs of the shapes codecs from other packages take -------------------------- + + +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 RecordingCodec: + """Records each direction it runs in, so a test can tell the codec was not skipped.""" + + calls: list[str] = field(default_factory=list, compare=False, hash=False) + + is_fixed_size = True + + def compute_encoded_size(self, input_byte_length: int, _chunk_spec: ArraySpec) -> int: + return input_byte_length + + +@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 + + 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._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) + + +@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`. + + Like a codec written before both the sync interface and prototypes. + """ + + def to_dict(self) -> dict[str, Any]: + return {"name": "test-async-only"} + + async def _encode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + 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: + self.calls.append("decode") + return default_buffer_prototype().buffer.from_bytes(chunk_bytes.to_bytes()) + + +@dataclass(frozen=True) +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 _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) + + +@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(), + Crc32cCodec(), + ] + + +def _numcodecs_chain() -> list[Codec]: + return [ + ExpectPrototypeCodec(), + zarr_numcodecs.Delta(dtype="int32"), + BytesCodec(), + zarr_numcodecs.Zlib(), + zarr_numcodecs.CRC32(), + ] + + +def _async_only_chain() -> list[Codec]: + """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 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(), + ] + + +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"), +] +# 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]: + """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. + + `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( + store, + zarr_format=2, + chunks=(2, 2), + filters=[numcodecs.Delta(dtype=" 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 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(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])] + + +def _host(array: Any) -> npt.NDArray[Any]: + return _to_host(array) if isinstance(array, DeviceArray) else np.asarray(array) + + +@pytest.mark.parametrize("pipeline", PIPELINES) +@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: + """Reads and writes produce the given prototype's buffer kind, whatever `zarr.config` names. + + 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. + """ + codecs = _no_chain() if layout == "v2" else CHAINS[chain]() + store = RecordingStore() + with config.set({**direction.buffer_config, "codec_pipeline.path": pipeline}): + 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(_host(got), expected) + assert store.chunk_value_types == {direction.prototype.buffer} + 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. 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( + shape=(2, 2), + dtype=zdtype, + fill_value=zdtype.cast_scalar(0), + config=ArrayConfig.from_dict({}), + prototype=direction.prototype, + ) + codec = V2Codec(filters=None, compressor=None) + data = np.arange(4, dtype="int32").reshape(2, 2) + chunk = direction.prototype.nd_buffer.from_numpy_array(data) + with config.set(direction.buffer_config): + encoded = codec._encode_sync(chunk, spec) + assert encoded is not None + decoded = codec._decode_sync(encoded, spec) + assert type(decoded) is direction.prototype.nd_buffer + np.testing.assert_array_equal(decoded.as_numpy_array(), data) + + +# `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( + ("direction", "layout", "chain"), _cases(UNUSABLE_CONFIG_DIRECTIONS, PROTOTYPE_LAYOUT_CHAINS) +) +def test_codecs_read_no_buffer_config( + 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`.""" + 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(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: + 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, + codecs: tuple[Codec, ...] = (BytesCodec(),), +) -> Any: + 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)]))) + + +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"] +) +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) + + +@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 AsyncOnlyRawFilterCodec(ArrayArrayCodec): + """A no-op codec whose decode returns a NumPy array, not an `NDBuffer`; async interface only.""" + + 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 + + def _encode_raw(self, chunk_array: NDBuffer, chunk_spec: ArraySpec) -> NDBuffer: + return chunk_array + + 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_raw(chunk_array, chunk_spec) + + async def _decode_single(self, chunk_array: Any, chunk_spec: ArraySpec) -> Any: + return self._decode_raw(chunk_array, chunk_spec) + + +@dataclass(frozen=True) +class AsyncOnlyRawSerializerCodec(ArrayBytesCodec): + """A codec whose decode takes `bytes` or a `Buffer` and returns a NumPy array; async only.""" + + 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 + + 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_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_raw(chunk_array, chunk_spec) + + async def _decode_single(self, chunk_bytes: Any, chunk_spec: ArraySpec) -> Any: + return self._decode_raw(chunk_bytes, chunk_spec) + + +@dataclass(frozen=True) +class AsyncOnlyRawBytesCodec(BytesBytesCodec): + """A no-op codec whose decode returns `bytes`, not a `Buffer`; async interface only.""" + + 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 + + def _encode_raw(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Buffer: + return chunk_bytes + + 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_raw(chunk_bytes, chunk_spec) + + async def _decode_single(self, chunk_bytes: Buffer, chunk_spec: ArraySpec) -> Any: + 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"]) +@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()] + 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: + 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]) diff --git a/tests/test_codecs/test_sharding_unit.py b/tests/test_codecs/test_sharding_unit.py index 978f7882f4..3f9cedca42 100644 --- a/tests/test_codecs/test_sharding_unit.py +++ b/tests/test_codecs/test_sharding_unit.py @@ -24,7 +24,7 @@ from zarr.core.array_spec import ArrayConfig, ArraySpec from zarr.core.buffer import Buffer as ABCBuffer from zarr.core.buffer import NDBuffer, default_buffer_prototype -from zarr.core.buffer.cpu import Buffer +from zarr.core.buffer.cpu import Buffer, buffer_prototype from zarr.core.buffer.cpu import NDBuffer as CPUNDBuffer from zarr.core.chunk_grids import ChunkGrid from zarr.core.config import config @@ -458,7 +458,7 @@ async def mock_load_index( def test_shard_reader_create_empty() -> 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,)]