diff --git a/Justfile b/Justfile index df96003eef..c8bd302531 100644 --- a/Justfile +++ b/Justfile @@ -57,7 +57,7 @@ coverage-serve *args: # Run slow Hypothesis tests and write coverage.xml hypothesis *args: - hatch run {{ quote(hatch_env) }}:coverage run --source=src -m pytest -nauto --run-slow-hypothesis tests/test_properties.py tests/test_store/test_stateful* tests/test_array_stateful.py "$@" + hatch run {{ quote(hatch_env) }}:coverage run --source=src -m pytest -nauto --run-slow-hypothesis tests/test_properties.py tests/test_store/test_stateful* tests/test_array_stateful.py tests/test_zarr_metadata_conformance.py "$@" hatch run {{ quote(hatch_env) }}:coverage xml # Validate executable documentation code blocks diff --git a/changes/4633.bugfix.1.md b/changes/4633.bugfix.1.md new file mode 100644 index 0000000000..a8293c2cd6 --- /dev/null +++ b/changes/4633.bugfix.1.md @@ -0,0 +1 @@ +Creating a sharded array no longer fails when the codecs inside the shard cannot encode the data type's default value, for example a `scale_offset` filter that maps only part of the data type's range. The inner codecs are now checked against the array's fill value, which must still be encodable. diff --git a/changes/4633.bugfix.2.md b/changes/4633.bugfix.2.md new file mode 100644 index 0000000000..2668b0532b --- /dev/null +++ b/changes/4633.bugfix.2.md @@ -0,0 +1 @@ +Creating or opening an array no longer rejects a codec placed after a data-type-changing codec such as `cast_value` because its configuration would be invalid for the array's original data type. Each codec is now checked against the data type it receives. diff --git a/pyproject.toml b/pyproject.toml index 97901a73df..562d6d4d48 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -123,6 +123,12 @@ test = [ "pytest-codspeed==5.0.4", "uv==0.13.10", ] +# tests/test_zarr_metadata_conformance.py draws array documents from zarr-metadata's +# strategies. Its own group, because zarr-metadata needs a newer typing-extensions than +# the `min_deps` env pins; the test skips where it is not installed. +conformance = [ + "zarr-metadata[testing]==0.9.0", +] remote-tests = [ {include-group = "test"}, "fsspec>=2023.10.0", @@ -156,6 +162,7 @@ docs = [ ] dev = [ {include-group = "test"}, + {include-group = "conformance"}, {include-group = "remote-tests"}, {include-group = "docs"}, "universal-pathlib", @@ -188,7 +195,7 @@ hooks.vcs.version-file = "src/zarr/_version.py" dependency-groups = ["dev"] [tool.hatch.envs.test] -dependency-groups = ["test"] +dependency-groups = ["test", "conformance"] [tool.hatch.envs.test.env-vars] diff --git a/src/zarr/codecs/sharding.py b/src/zarr/codecs/sharding.py index d4ccf71cb9..dc168926f1 100644 --- a/src/zarr/codecs/sharding.py +++ b/src/zarr/codecs/sharding.py @@ -588,27 +588,47 @@ def to_dict(self) -> dict[str, JSON]: } def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: - """Thread the spec through the inner chain. + """Evolve and validate the inner chain against the chunks it encodes. - Each codec is evolved against the spec produced by the previous one. - Evolving every codec against the same unthreaded spec is the bug shape that - strips `BytesCodec.endian` behind a dtype-changing codec — and this - method runs on the real array-creation path, baking the damaged chain - into the evolved instance before the transform builders ever run. + Each inner codec is evolved against, validated against, and resolved through + the spec the codecs before it leave, as array metadata does for its own codecs, + with a regular grid of one inner chunk as its chunk grid. A sharding codec among + them is thereby checked against the chunk it splits. + + The spec is threaded for two reasons. A dtype-changing codec changes what the + codecs after it see: evolving every codec against the unthreaded spec strips + `BytesCodec.endian` behind one. And the fill value the inner chain must encode + is the array's fill value as the codecs before this one leave it, which is what + an unwritten inner chunk holds. Probing the chain with any other value, such as + the data type's default scalar, rejects chains that never see that value. Parameters ---------- array_spec - The base spec to be evolved as we thread it. + The spec of the shards this codec encodes. Returns ------- - This codec with the evolved code chain. - """ - from zarr.core.chunk_utils import evolve_codecs + This codec with the evolved codec chain. - shard_spec = self._get_chunk_spec(array_spec) - evolved_codecs = evolve_codecs(self.codecs, shard_spec) + Raises + ------ + ValueError + If an inner codec is incompatible with the chunk it encodes, or cannot + encode the fill value it receives. + """ + evolved: list[Codec] = [] + spec = self._get_chunk_spec(array_spec) + for codec in self.codecs: + evolved_codec = codec.evolve_from_array_spec(spec) + evolved_codec.validate( + shape=spec.shape, + dtype=spec.dtype, + chunk_grid=RegularChunkGridMetadata(chunk_shape=spec.shape), + ) + evolved.append(evolved_codec) + spec = evolved_codec.resolve_metadata(spec) + evolved_codecs = tuple(evolved) if evolved_codecs != self.codecs: return replace(self, codecs=evolved_codecs) return self @@ -635,35 +655,20 @@ def validate( f"Sharding is only compatible with regular and rectilinear chunk grids, " f"got {type(chunk_grid)}" ) - for i, (edges, inner) in enumerate(zip(edges_per_dim, self.chunk_shape, strict=False)): + # A codec before this one can change the number of dimensions, while `chunk_grid` + # is still the array's own. Its edges then say nothing about the shards. + if len(edges_per_dim) != len(self.chunk_shape): + raise ValueError( + f"The shard's `chunk_shape` has rank {len(self.chunk_shape)}, but the " + f"array's chunk grid has rank {len(edges_per_dim)}." + ) + for i, (edges, inner) in enumerate(zip(edges_per_dim, self.chunk_shape, strict=True)): for edge in set(edges): if edge % inner != 0: raise ValueError( f"Chunk edge length {edge} in dimension {i} is not " f"divisible by the shard's inner chunk size {inner}." ) - self._validate_inner_codecs(dtype) - - def _validate_inner_codecs(self, dtype: ZDType[TBaseDType, TBaseScalar]) -> None: - """Validate the codecs that encode each inner chunk, as array metadata validates - its codecs: each against the chunk the codecs before it leave it, a regular - grid of one inner chunk. A sharding codec among them is thereby checked against - the chunk it splits, which `validate` of the outer codec alone does not see. - """ - spec = ArraySpec( - shape=self.chunk_shape, - dtype=dtype, - fill_value=dtype.default_scalar(), - config=ArrayConfig.from_dict({}), - prototype=default_buffer_prototype(), - ) - for codec in self.codecs: - codec.validate( - shape=spec.shape, - dtype=spec.dtype, - chunk_grid=RegularChunkGridMetadata(chunk_shape=spec.shape), - ) - spec = codec.resolve_metadata(spec) def _get_inner_chunk_transform(self, shard_spec: ArraySpec) -> Any: """The synchronous transform for the inner codec chain. diff --git a/src/zarr/core/metadata/v3.py b/src/zarr/core/metadata/v3.py index 63d525ba2d..23c235ec75 100644 --- a/src/zarr/core/metadata/v3.py +++ b/src/zarr/core/metadata/v3.py @@ -570,6 +570,9 @@ def __init__( # Per-codec validate() must run before resolve_metadata(), since the # latter may rely on invariants the former checks (e.g. cast_value # rejects complex source dtypes that would otherwise crash _do_cast). + # Codecs validate against the chunk grid, so its rank must be checked first. + if len(shape_parsed) != chunk_grid_parsed.ndim: + raise ValueError("`chunk_grid` and `shape` need to have the same number of dimensions.") evolved: list[Codec] = [] spec = array_spec for c in codecs_parsed_partial: @@ -594,8 +597,6 @@ def __init__( self._validate_metadata() def _validate_metadata(self) -> None: - if len(self.shape) != self.chunk_grid.ndim: - raise ValueError("`chunk_grid` and `shape` need to have the same number of dimensions.") if isinstance(self.chunk_grid, RectilinearChunkGridMetadata): validate_rectilinear_edges(self.chunk_grid.chunk_shapes, self.shape) if self.dimension_names is not None and len(self.shape) != len(self.dimension_names): @@ -604,8 +605,9 @@ def _validate_metadata(self) -> None: ) if self.fill_value is None: raise ValueError("`fill_value` is required.") - for codec in self.codecs: - codec.validate(shape=self.shape, dtype=self.data_type, chunk_grid=self.chunk_grid) + # The codecs were validated in `__init__`, each against the spec the codecs + # before it leave. Validating them again here against the array's own data type + # would reject a codec that only ever sees the output of a dtype-changing codec. @property def ndim(self) -> int: diff --git a/tests/test_codecs/test_cast_value.py b/tests/test_codecs/test_cast_value.py index d6c703767f..37d1cb385a 100644 --- a/tests/test_codecs/test_cast_value.py +++ b/tests/test_codecs/test_cast_value.py @@ -8,7 +8,7 @@ import zarr from tests.conftest import Expect, ExpectFail -from zarr.codecs import BytesCodec, TransposeCodec +from zarr.codecs import BytesCodec, ScaleOffset, TransposeCodec from zarr.codecs.cast_value import CAST_VALUE_RS_MIN_VERSION, CastValue from zarr.storage import MemoryStore @@ -610,3 +610,24 @@ def make_array(filters: list[Any]) -> Any: array[:] = data assert_array_equal(array[:], data) + + +@requires_cast_value_rs +@pytest.mark.parametrize("shards", [None, (8,)], ids=["unsharded", "sharded"]) +def test_codec_validated_against_the_dtype_it_sees(shards: tuple[int, ...] | None) -> None: + """A codec behind `cast_value` is validated against the cast's target data type, + not the array's: a `scale_offset` scale of 0.5 is representable in float32, which + the codec sees, though not in the array's int16.""" + store = MemoryStore() + data = np.arange(8, dtype="int16") + arr = zarr.create_array( + store, + shape=data.shape, + dtype=data.dtype, + chunks=(4,), + shards=shards, + filters=[CastValue(data_type="float32"), ScaleOffset(scale=0.5)], + compressors=None, + ) + arr[:] = data + assert_array_equal(zarr.open_array(store, mode="r")[:], data) diff --git a/tests/test_codecs/test_sharding.py b/tests/test_codecs/test_sharding.py index 0c62c8368f..c4a8809133 100644 --- a/tests/test_codecs/test_sharding.py +++ b/tests/test_codecs/test_sharding.py @@ -19,10 +19,11 @@ BytesCodec, Crc32cCodec, GzipCodec, + ScaleOffset, ShardingCodec, TransposeCodec, ) -from zarr.codecs.numcodecs import CRC32 +from zarr.codecs.numcodecs import CRC32, PackBits from zarr.codecs.sharding import ( INDEX_LOCATION, MAX_UINT_64, @@ -1522,3 +1523,105 @@ def test_open_rejects_stored_nested_sharding_with_indivisible_inner_chunk_shape( doc["codecs"][0]["configuration"]["codecs"][0]["configuration"]["chunk_shape"] = (4, 7) with pytest.raises(ValueError, match="not divisible"): ArrayV3Metadata.from_dict(doc) + + +# Each layout pairs codecs with a fill value the inner chain can encode, as the codecs +# before it leave that value, and one it cannot. The accepted fill value is chosen so +# that neither the data type's default scalar (0) nor, where a filter precedes the +# sharding codec, the array's fill value as given would pass the inner chain. +_INNER_CHAIN_FILL_LAYOUTS: dict[str, tuple[dict[str, Any], int, int]] = { + # `scale_offset` inside the shard: the inner chain encodes [100, 65535]. + "inside-shard": ( + {"chunks": (4,), "shards": (16,), "filters": [ScaleOffset(offset=100)]}, + 100, + 0, + ), + # `scale_offset` before the sharding codec doubles the fill value, so the inner + # chain sees 120 for an array fill value of 60, and 80 for 40. Its own + # `scale_offset` encodes [100, 65535]. + "behind-filter": ( + { + "chunks": (16,), + "filters": [ScaleOffset(scale=2)], + "serializer": ShardingCodec( + chunk_shape=(4,), codecs=[ScaleOffset(offset=100), BytesCodec()] + ), + }, + 60, + 40, + ), + # The fill value reaches a sharding codec nested in another one. + "nested": ( + { + "chunks": (16,), + "serializer": ShardingCodec( + chunk_shape=(8,), + codecs=[ + ShardingCodec(chunk_shape=(4,), codecs=[ScaleOffset(offset=100), BytesCodec()]) + ], + ), + }, + 100, + 0, + ), +} + + +@pytest.mark.filterwarnings( + "ignore:Combining a `sharding_indexed` codec:zarr.errors.ZarrUserWarning" +) +@pytest.mark.parametrize("layout", _INNER_CHAIN_FILL_LAYOUTS) +def test_sharding_inner_chain_probed_with_array_fill_value(layout: str) -> None: + """A sharding codec's inner chain is validated against the array's fill value, as + the codecs before it leave it, not against the data type's default scalar + (https://github.com/zarr-developers/zarr-python/issues/4511). The array is created, + reads its fill value before any write, and round-trips a partial write.""" + codecs, fill_value, _ = _INNER_CHAIN_FILL_LAYOUTS[layout] + store = MemoryStore() + arr = zarr.create_array( + store, shape=(16,), dtype="uint16", fill_value=fill_value, compressors=None, **codecs + ) + expected = np.full(16, fill_value, dtype="uint16") + np.testing.assert_array_equal(arr[:], expected) + written = np.arange(110, 114, dtype="uint16") + arr[4:8] = written + expected[4:8] = written + np.testing.assert_array_equal(zarr.open_array(store, mode="r")[:], expected) + + +@pytest.mark.filterwarnings( + "ignore:Combining a `sharding_indexed` codec:zarr.errors.ZarrUserWarning" +) +@pytest.mark.parametrize("layout", _INNER_CHAIN_FILL_LAYOUTS) +def test_sharding_rejects_fill_value_inner_chain_cannot_encode(layout: str) -> None: + """An array whose fill value the inner chain cannot encode is rejected: an + unwritten inner chunk holds the fill value, so the array could not be read before + its first write.""" + codecs, _, fill_value = _INNER_CHAIN_FILL_LAYOUTS[layout] + with pytest.raises(ValueError, match="outside the range"): + zarr.create_array( + MemoryStore(), + shape=(16,), + dtype="uint16", + fill_value=fill_value, + compressors=None, + **codecs, + ) + + +@pytest.mark.filterwarnings("ignore:Numcodecs codecs are not in the Zarr version 3 specification") +def test_sharding_rejects_filter_that_changes_the_number_of_dimensions() -> None: + """A sharding codec behind a filter that flattens each chunk is rejected: the array's + chunk grid, which the inner chunk shape is checked against, says nothing about the + flattened chunk. Accepting it lost the end of each chunk whose flattened length the + inner chunk size did not divide.""" + with pytest.raises(ValueError, match="has rank 1, but the array's chunk grid has rank 2"): + zarr.create_array( + MemoryStore(), + shape=(8, 8), + chunks=(8, 8), + dtype="bool", + filters=[PackBits()], + serializer=ShardingCodec(chunk_shape=(8,)), + compressors=None, + ) diff --git a/tests/test_zarr_metadata_conformance.py b/tests/test_zarr_metadata_conformance.py new file mode 100644 index 0000000000..f91c8a6497 --- /dev/null +++ b/tests/test_zarr_metadata_conformance.py @@ -0,0 +1,352 @@ +"""zarr-python's verdict on the array documents zarr-metadata's strategies draw. + +zarr-metadata's strategies draw documents that the spec allows. Each codec in them +is drawn for the data type and the chunk the codecs before it hand on, so new codecs +and nestings are covered as soon as zarr-metadata defines them. + +zarr-python refuses one kind of valid document on purpose: one whose fill value the +codecs cannot encode, because an unwritten chunk holds the fill value. The test decides +which documents those are by encoding a chunk that holds the fill value. A document +refused although its fill value encodes, or accepted although it does not, is a bug. + +The codecs themselves are the reference, so a codec that is wrong in the same way when +it encodes a chunk and when it encodes the fill value is not caught here. + +`_DIVERGENCES` lists the known divergences from the spec. The strategies here leave out +each one they can, and a strict xfail test below pins each one, so that fixing it fails +that test and prompts removing the exclusion. +""" + +from __future__ import annotations + +import dataclasses +import importlib.util +import json +import warnings +from functools import partial +from typing import TYPE_CHECKING, Any, Final + +import numpy as np +import pytest + +# Not installed in the `min_deps` env: see the `conformance` dependency group. +pytest.importorskip("zarr_metadata.testing") + +from hypothesis import event, given, reject, settings +from hypothesis import strategies as st +from zarr_metadata.definition import canonical_of, resolve +from zarr_metadata.testing.strategies import ( + DEFAULT_STRATEGIES, + ChunkGridStrategy, + array_documents, +) +from zarr_metadata.v3.chunk_grid import RECTILINEAR_CHUNK_GRID +from zarr_metadata.v3.codec import CAST_VALUE_CODEC +from zarr_metadata.v3.data_type import RAW_BYTES_DATA_TYPE +from zarr_metadata.v3.definition import ( + CORE_AND_EXTENSIONS_CONTEXT, + ChunkGridDefinition, + CodecDefinition, + DataTypeDefinition, +) + +import zarr +from zarr.abc.codec import ArrayArrayCodec, SupportsSyncCodec +from zarr.core.array_spec import ArrayConfig, ArraySpec +from zarr.core.buffer import default_buffer_prototype +from zarr.core.dtype import get_data_type_from_json, get_data_type_from_native_dtype +from zarr.core.metadata.v3 import ArrayV3Metadata, parse_codecs + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping + + from zarr_metadata.testing.strategies import Configurations, Strategies + +_HAS_CAST_VALUE_RS: Final = importlib.util.find_spec("cast_value_rs") is not None + +_DIVERGENCES: Final = { + "data type spellings": ( + "A data type written as an object, such as `{'name': 'int8'}` or one with " + "`must_understand`, is refused. Data types are written in their simplest spelling." + ), + "raw bits": "The core `r*` data types are not implemented. None are drawn.", + "sharding behind transpose": ( + "A sharding codec after a `transpose` is validated against the untransposed " + "chunk. No document with a transpose that moves an axis before one is tested." + ), + "cast_value hex scalar map": ( + "A `scalar_map` entry that writes a float as a hex string is refused while a value " + "is cast, whether or not the entry maps that value. Encoding the fill value fails " + "the same way, so the property does not see it. Not excluded." + ), + "expanded rectilinear runs": ( + "zarr-python expands each run-length pair of rectilinear edges into a list, so a " + "valid run of many chunks exhausts memory. No grid listing more than " + "`_MAX_LISTED_CHUNKS` chunks along an axis is drawn." + ), +} + +_MAX_LISTED_CHUNKS: Final = 10_000 + + +def _listed_chunks(dimension: Any) -> int: + """How many chunks a dimension's edges list, counting each run; 0 for a bare length.""" + if isinstance(dimension, int): + return 0 + return sum(edge[1] if isinstance(edge, tuple | list) else 1 for edge in dimension) + + +def _readable(configuration: Mapping[str, Any]) -> bool: + """Whether zarr-python reads the rectilinear grid without a known divergence.""" + return all( + _listed_chunks(dimension) <= _MAX_LISTED_CHUNKS + for dimension in configuration["chunk_shapes"] + ) + + +def _readable_grids( + configurations: Callable[[tuple[int, ...] | None, Strategies], Configurations], + shape: tuple[int, ...] | None, + strategies: Strategies, +) -> Configurations: + return configurations(shape, strategies).filter(_readable) + + +def _supported(strategies: Strategies) -> Strategies: + """`strategies` without the known divergences in `_DIVERGENCES`.""" + out = { + definition: strategy + for definition, strategy in strategies.items() + if definition is not RAW_BYTES_DATA_TYPE + and (_HAS_CAST_VALUE_RS or definition is not CAST_VALUE_CODEC) + } + grid_strategy = out.get(RECTILINEAR_CHUNK_GRID) + if isinstance(grid_strategy, ChunkGridStrategy): + out[RECTILINEAR_CHUNK_GRID] = dataclasses.replace( + grid_strategy, configurations=partial(_readable_grids, grid_strategy.configurations) + ) + return out + + +_VALUE_DATA_TYPES: Final = frozenset( + {"int8", "uint8", "int16", "uint16", "int32", "uint32", "float32", "float64"} +) +_VALUE_CODECS: Final = frozenset( + {"bytes", "cast_value", "scale_offset", "sharding_indexed", "transpose"} +) + + +def _value_transforming(strategies: Strategies) -> Strategies: + """Integer and float data types, regular grids, and the codecs that change values. + + In this slice a fill value is often one the codecs cannot encode, which is where + zarr-python's one deliberate refusal is decided. + """ + return { + definition: strategy + for definition, strategy in strategies.items() + if not ( + isinstance(definition, DataTypeDefinition) and definition.name not in _VALUE_DATA_TYPES + ) + and not (isinstance(definition, CodecDefinition) and definition.name not in _VALUE_CODECS) + and not (isinstance(definition, ChunkGridDefinition) and definition.name != "regular") + } + + +_DOCUMENTS: Final = { + "every-definition": array_documents(strategies=_supported(DEFAULT_STRATEGIES)), + "value-transforming": array_documents( + shapes=st.lists(st.integers(1, 16), min_size=1, max_size=2).map(tuple), + strategies=_value_transforming(_supported(DEFAULT_STRATEGIES)), + ), +} + + +def _codec_name(codec: str | Mapping[str, Any]) -> str: + return codec if isinstance(codec, str) else codec["name"] + + +def _moves_an_axis(codec: str | Mapping[str, Any]) -> bool: + if isinstance(codec, str) or codec["name"] != "transpose": + return False + order = codec["configuration"]["order"] + return list(order) != sorted(order) + + +def _shard_behind_transpose(codecs: list[Any]) -> bool: + """Whether a transpose that moves an axis precedes the array's own sharding codec. + + Only the array's own codecs: inside a shard, each codec is validated against the + chunk the codecs before it leave. + """ + return any(map(_moves_an_axis, codecs)) and "sharding_indexed" in map(_codec_name, codecs) + + +def _simplest_data_type(data_type: Any) -> Any: + read, problems = resolve(data_type, DataTypeDefinition, CORE_AND_EXTENSIONS_CONTEXT) + return json.loads(json.dumps(canonical_of(read, problems))) + + +def _simplest_data_types(codecs: list[Any]) -> None: + """Write each data type a `cast_value` casts to in its simplest spelling, in place.""" + for codec in codecs: + if _codec_name(codec) == "cast_value": + configuration = codec["configuration"] + configuration["data_type"] = _simplest_data_type(configuration["data_type"]) + elif _codec_name(codec) == "sharding_indexed": + _simplest_data_types(codec["configuration"]["codecs"]) + _simplest_data_types(codec["configuration"]["index_codecs"]) + + +def _array_array_codecs(codecs: list[Any]) -> list[ArrayArrayCodec]: + """The codecs that transform an array on its way to bytes: the array's own, then the shards'.""" + out: list[ArrayArrayCodec] = [] + for declaration in codecs: + if _codec_name(declaration) == "sharding_indexed": + return out + _array_array_codecs(declaration["configuration"]["codecs"]) + (codec,) = parse_codecs([declaration]) + if isinstance(codec, ArrayArrayCodec): + out.append(codec) + return out + + +def _fill_value_encodes(document: dict[str, Any]) -> bool: + """Whether the codecs encode a chunk of one element, the fill value.""" + data_type = get_data_type_from_json(document["data_type"], zarr_format=3) + fill_value = data_type.from_json_scalar(document["fill_value"], zarr_format=3) + chunk = np.full((1,) * len(document["shape"]), fill_value, dtype=data_type.to_native_dtype()) + prototype = default_buffer_prototype() + for codec in _array_array_codecs(document["codecs"]): + spec = ArraySpec( + shape=chunk.shape, + dtype=data_type, + fill_value=chunk.reshape(-1)[0], + config=ArrayConfig.from_dict({}), + prototype=prototype, + ) + evolved = codec.evolve_from_array_spec(spec) + assert isinstance(evolved, SupportsSyncCodec) + try: + encoded = evolved._encode_sync(prototype.nd_buffer.from_numpy_array(chunk), spec) + except ValueError: + return False + assert encoded is not None + before, chunk = chunk, encoded.as_numpy_array() + if chunk.dtype != before.dtype: + data_type = get_data_type_from_native_dtype(chunk.dtype) + return True + + +def _refusal(document: dict[str, Any]) -> Exception | None: + """The error zarr-python refuses `document` with, or None if it accepts it.""" + try: + ArrayV3Metadata.from_dict(document) + except Exception as error: # noqa: BLE001 + return error + return None + + +# Few documents tell a right verdict from a wrong one, so the profiles' 300 examples often +# miss a bug. With 2000, each slice caught an inner chain probed with the data type's +# default scalar, and codecs re-validated against the array's own data type, for at least +# 16 of 20 random seeds. +@settings(max_examples=2000) +@pytest.mark.parametrize("slice_", list(_DOCUMENTS)) +@given(data=st.data()) +def test_refuses_exactly_the_fill_values_the_codecs_cannot_encode( + slice_: str, data: st.DataObject +) -> None: + """zarr-python refuses a document if, and only if, the codecs cannot encode its fill value.""" + # As a reader sees it: zarr-metadata draws JSON arrays as tuples. + document = json.loads(json.dumps(data.draw(_DOCUMENTS[slice_]))) + if _shard_behind_transpose(document["codecs"]): + reject() # "sharding behind transpose" in _DIVERGENCES + document["data_type"] = _simplest_data_type(document["data_type"]) + _simplest_data_types(document["codecs"]) + with warnings.catch_warnings(), zarr.config.set({"array.rectilinear_chunks": True}): + # numpy warns when it computes with NaN and infinity. + warnings.simplefilter("ignore") + encodes = _fill_value_encodes(document) + error = _refusal(document) + event("fill value encodes" if encodes else "fill value does not encode") + if encodes: + assert error is None, f"zarr-python refuses a document the spec allows: {error!r}" + else: + assert isinstance(error, ValueError) + + +def _document( + data_type: Any, fill_value: Any, codecs: list[Any], chunk_shape: tuple[int, ...] = (4,) +) -> dict[str, Any]: + return { + "zarr_format": 3, + "node_type": "array", + "shape": chunk_shape, + "data_type": data_type, + "fill_value": fill_value, + "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": chunk_shape}}, + "chunk_key_encoding": {"name": "default"}, + "codecs": codecs, + } + + +@pytest.mark.xfail(strict=True, raises=ValueError, reason=_DIVERGENCES["data type spellings"]) +@pytest.mark.parametrize( + "data_type", + [ + {"name": "int8"}, + {"name": "int8", "configuration": {}}, + {"name": "int8", "must_understand": True}, + ], +) +def test_data_type_object_spelling(data_type: dict[str, Any]) -> None: + ArrayV3Metadata.from_dict(_document(data_type, 0, [{"name": "bytes"}])) + + +@pytest.mark.xfail(strict=True, raises=ValueError, reason=_DIVERGENCES["raw bits"]) +def test_raw_bits_data_type() -> None: + ArrayV3Metadata.from_dict(_document("r16", [0, 0], [{"name": "bytes"}])) + + +@pytest.mark.xfail(strict=True, raises=ValueError, reason=_DIVERGENCES["sharding behind transpose"]) +def test_sharding_behind_transpose() -> None: + # The transposed chunk is (4, 2), which inner chunks of (4, 1) divide. + sharding = { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": (4, 1), + "codecs": [{"name": "bytes", "configuration": {"endian": "little"}}], + "index_codecs": [{"name": "bytes", "configuration": {"endian": "little"}}], + }, + } + transpose = {"name": "transpose", "configuration": {"order": (1, 0)}} + ArrayV3Metadata.from_dict(_document("uint8", 0, [transpose, sharding], chunk_shape=(2, 4))) + + +@pytest.mark.skipif(not _HAS_CAST_VALUE_RS, reason="cast-value-rs not installed") +@pytest.mark.xfail(strict=True, raises=ValueError, reason=_DIVERGENCES["cast_value hex scalar map"]) +def test_cast_value_scalar_map_hex_float() -> None: + cast = { + "name": "cast_value", + "configuration": { + "data_type": "float32", + "scalar_map": {"encode": [[1, "0x7fc00000"]]}, + }, + } + ArrayV3Metadata.from_dict( + _document("uint8", 0, [cast, {"name": "bytes", "configuration": {"endian": "little"}}]) + ) + + +@pytest.mark.xfail( + strict=True, raises=MemoryError, reason=_DIVERGENCES["expanded rectilinear runs"] +) +def test_rectilinear_run_is_not_expanded() -> None: + """A run of 2**62 chunks of length 2 is read without listing them.""" + document = _document("uint8", 0, [{"name": "bytes"}], chunk_shape=(2**63 - 1,)) + document["chunk_grid"] = { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[2, 2**62]]]}, + } + with zarr.config.set({"array.rectilinear_chunks": True}): + ArrayV3Metadata.from_dict(document) diff --git a/uv.lock b/uv.lock index 856be74a78..fa0928715a 100644 --- a/uv.lock +++ b/uv.lock @@ -3831,6 +3831,9 @@ remote = [ ] [package.dev-dependencies] +conformance = [ + { name = "zarr-metadata", extra = ["testing"] }, +] dev = [ { name = "astroid" }, { name = "botocore" }, @@ -3863,6 +3866,7 @@ dev = [ { name = "towncrier" }, { name = "universal-pathlib" }, { name = "uv" }, + { name = "zarr-metadata", extra = ["testing"] }, ] docs = [ { name = "astroid" }, @@ -3935,6 +3939,7 @@ requires-dist = [ provides-extras = ["cast-value-rs", "cli", "gpu", "optional", "remote"] [package.metadata.requires-dev] +conformance = [{ name = "zarr-metadata", extras = ["testing"], specifier = "==0.9.0" }] dev = [ { name = "astroid", specifier = "==4.3.4" }, { name = "botocore" }, @@ -3967,6 +3972,7 @@ dev = [ { name = "towncrier", specifier = "==26.9.0" }, { name = "universal-pathlib" }, { name = "uv", specifier = "==0.13.10" }, + { name = "zarr-metadata", extras = ["testing"], specifier = "==0.9.0" }, ] docs = [ { name = "astroid", specifier = "==4.3.4" }, @@ -4017,3 +4023,21 @@ test = [ { name = "pytest-xdist", specifier = "==3.8.0" }, { name = "uv", specifier = "==0.13.10" }, ] + +[[package]] +name = "zarr-metadata" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7f/5d/5f1778697e0022d5cf7b215554a96827949a1d065b51913059b83b770ab3/zarr_metadata-0.9.0.tar.gz", hash = "sha256:7c7612ccb0177f2d1abb05cc38cdb89a54f31558edccf78d848a1c68d95415f7", size = 616077, upload-time = "2026-11-16T13:12:44.238Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/35/26/c1eb0a10cbbe9cc7d759ee66261f2461f09e964359dd4d3e6a0c74824bba/zarr_metadata-0.9.0-py3-none-any.whl", hash = "sha256:61714b08a7eacd4bef4e1ccc485e331de2ac5b7afda624094a711e474641338a", size = 339074, upload-time = "2026-11-16T13:12:42.616Z" }, +] + +[package.optional-dependencies] +testing = [ + { name = "hypothesis" }, +]