From eac011a4df023d1493fc52194389ede9d4a58877 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 27 Sep 2026 16:42:45 +0200 Subject: [PATCH 1/3] feat(zarr-metadata)!: a chunk grid is judged against the shape it chunks A chunk grid's definition says which arrays it fits, and the v3 array validators judge a document's grid against its shape once both are read: a regular grid has a chunk length for each dimension, and 0 only for a dimension of length 0; a rectilinear grid has chunk lengths for each dimension that cover it. Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-metadata/README.md | 3 +- .../changes/+layer-4b.feature.md | 7 ++ packages/zarr-metadata/docs/index.md | 3 +- .../src/zarr_metadata/model/__init__.py | 3 +- .../src/zarr_metadata/model/_array.py | 5 +- .../src/zarr_metadata/model/_validation.py | 53 ++++---- .../src/zarr_metadata/v3/_definition.py | 50 ++++++-- .../v3/chunk_grid/rectilinear.py | 34 ++++- .../zarr_metadata/v3/chunk_grid/regular.py | 40 +++++- .../zarr_metadata/v3/data_type/_numpy_time.py | 2 +- .../src/zarr_metadata/v3/data_type/struct.py | 2 +- .../src/zarr_metadata/v3/definition.py | 24 ++-- .../zarr-metadata/tests/model/test_array.py | 3 +- .../tests/v3/test_definitions.py | 16 ++- .../tests/v3/test_grid_shapes.py | 117 ++++++++++++++++++ 15 files changed, 300 insertions(+), 62 deletions(-) create mode 100644 packages/zarr-metadata/changes/+layer-4b.feature.md create mode 100644 packages/zarr-metadata/tests/v3/test_grid_shapes.py diff --git a/packages/zarr-metadata/README.md b/packages/zarr-metadata/README.md index a669ea370b..a2e7690a61 100644 --- a/packages/zarr-metadata/README.md +++ b/packages/zarr-metadata/README.md @@ -65,8 +65,9 @@ configuration its definition refuses is refused, and a key it does not declare is reported as `unknown_key`. A name nothing in the scope claims is left unjudged, and whether to support it is the consumer's decision. A v3 fill value is judged against the data type it names, by that data type's +definition, and the chunk grid against the shape, by the grid's definition. The validators do not judge a codec against the array it is -handed, or a chunk grid against the shape. +handed. The Pydantic integration's generated JSON Schemas express independently checkable document structure and field constraints, but they are not a diff --git a/packages/zarr-metadata/changes/+layer-4b.feature.md b/packages/zarr-metadata/changes/+layer-4b.feature.md new file mode 100644 index 0000000000..b899c84f09 --- /dev/null +++ b/packages/zarr-metadata/changes/+layer-4b.feature.md @@ -0,0 +1,7 @@ +**Breaking:** a v3 array's `chunk_grid` is judged against its `shape`, by +the grid's definition. A regular grid whose `chunk_shape` does not have +one length per dimension of the shape, or has a length of 0 for a +dimension that is not empty, and a rectilinear grid whose `chunk_shapes` +does not have one entry per dimension, or whose chunk lengths fall short +of their dimension, each have a problem in `chunk_grid.configuration`, +where the package accepted them before. diff --git a/packages/zarr-metadata/docs/index.md b/packages/zarr-metadata/docs/index.md index 497b43c11d..a79f2bf729 100644 --- a/packages/zarr-metadata/docs/index.md +++ b/packages/zarr-metadata/docs/index.md @@ -80,8 +80,9 @@ configuration its definition refuses is refused, and a key it does not declare is reported as `unknown_key`. A name nothing in the scope claims is left unjudged, and whether to support it is the consumer's decision. A v3 fill value is judged against the data type it names, by that data type's +definition, and the chunk grid against the shape, by the grid's definition. The validators do not judge a codec against the array it is -handed, or a chunk grid against the shape. +handed. ## Scope diff --git a/packages/zarr-metadata/src/zarr_metadata/model/__init__.py b/packages/zarr-metadata/src/zarr_metadata/model/__init__.py index 2c2c6c849d..18eebef5ba 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/__init__.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/__init__.py @@ -5,7 +5,8 @@ structure and, in a v3 document, read each extension point (codecs, chunk grids, data types, ...) through the definition that claims its name in a scope, `CORE_AND_EXTENSIONS` unless a `context` is passed, and judge the -fill value against the data type it names. Each document concept gets a +fill value against the data type it names and the chunk grid against +the shape. Each document concept gets a `validate_*` function returning every problem found (a tuple of `ValidationProblem`, each with a machine-readable `kind`), an `is_*` type guard, and a `parse_*` function that narrows or raises diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_array.py b/packages/zarr-metadata/src/zarr_metadata/model/_array.py index e7c585c684..6161d34eb2 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_array.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_array.py @@ -198,8 +198,9 @@ def create_default(cls, **overrides: Unpack[ZarrV3ArrayMetadataPartial]) -> Zarr it would require interpreting the grid's configuration, which this layer never does (and cannot do for unrecognized grid names). So overriding `chunk_grid` without `shape` keeps the scalar default - `shape=()`, and consistency between the two is the caller's - responsibility. So is a fill value for an overridden `data_type`: + `shape=()`, which a grid of another rank does not fit: consistency + between the two is the caller's responsibility, so pass them + together. So is a fill value for an overridden `data_type`: the default `fill_value` is `0`, which a data type whose fill value is not an integer -- `bool`, `string`, a complex or struct type -- refuses, so pass the two together. diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_validation.py b/packages/zarr-metadata/src/zarr_metadata/model/_validation.py index 5c83f262c2..65ff07c1dc 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_validation.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_validation.py @@ -5,8 +5,8 @@ each extension point through the definition that claims its name in a scope, so a configuration its definition refuses is refused here too. A name nothing in the scope claims is left unjudged. A v3 fill value is -judged against the data type it names; a codec against the array it is -handed, and a grid against the shape, are not judged here. Each concept +judged against the data type it names, and the chunk grid against the +shape; a codec against the array it is handed is not judged here. Each concept gets a `validate_*` function returning every problem found, an `is_*` type guard, and a `parse_*` function that narrows or raises `MetadataValidationError`. The guards are `TypeGuard`s, @@ -45,6 +45,7 @@ Definition, Resolved, StorageTransformerDefinition, + chunk_grid_problems, fill_value_problems, resolve, ) @@ -183,19 +184,22 @@ def _is_int_sequence(value: object) -> TypeGuard[Sequence[int]]: ) -def _validate_dim_sequence(doc: Mapping[object, object], key: str) -> tuple[ValidationProblem, ...]: - """Validate a dimension sequence (`shape` / `chunks`) if present in `doc`. +def _dimension_lengths( + doc: Mapping[object, object], key: str +) -> tuple[tuple[int, ...] | None, tuple[ValidationProblem, ...]]: + """The dimension lengths `doc` holds at `key` (`shape`, `chunks`), and every problem with them. - Dimension lengths are non-negative integers. + Dimension lengths are non-negative integers; the lengths are None when + `doc` holds none at `key`, or ones with a problem. """ if key not in doc: - return () + return None, () value = doc[key] if not _is_int_sequence(value): - return (ValidationProblem((key,), "expected a sequence of int", "invalid_type"),) + return None, (ValidationProblem((key,), "expected a sequence of int", "invalid_type"),) if any(item < 0 for item in value): - return (ValidationProblem((key,), "expected non-negative integers", "invalid_value"),) - return () + return None, (ValidationProblem((key,), "expected non-negative integers", "invalid_value"),) + return tuple(value), () def _is_dtype_v2(value: object) -> bool: @@ -349,9 +353,11 @@ def validate_array_metadata_v3( Its structure, and each extension point read through the definition that claims its name in `context`: a gzip `level` out of range, a key a codec's configuration does not declare. The fill value is judged - against the data type as `context` read it: an `int8` fill value of 300. - A name nothing in `context` claims is left unjudged, with any fill value - of it. Unknown top-level keys are allowed (they map + against the data type as `context` read it -- an `int8` fill value of + 300 -- and the chunk grid against the shape: a regular grid with a + chunk length for each of two dimensions, over an array of three. A name + nothing in `context` claims is left unjudged, with any fill value of + it. Unknown top-level keys are allowed (they map to `extra_fields`); a reader must understand each one that does not say `must_understand: false`, which the model reports as `must_understand_fields`. @@ -363,7 +369,8 @@ def validate_array_metadata_v3( problems.extend(_validate_other_members(doc, ARRAY_METADATA_STANDARD_KEYS_V3)) problems.extend(_check_literal(doc, "zarr_format", 3)) problems.extend(_check_literal(doc, "node_type", "array")) - problems.extend(_validate_dim_sequence(doc, "shape")) + shape, shape_problems = _dimension_lengths(doc, "shape") + problems.extend(shape_problems) # Each extension point is read by `resolve`, which judges its envelope # -- every extension *point* must be understood, so a `must_understand` # of `false` is refused at each: ignoring a codec gives wrong bytes as @@ -389,6 +396,9 @@ def validate_array_metadata_v3( ) else: problems.extend(_prefix("fill_value", validate_json(doc["fill_value"]))) + # The chunk grid is judged against the shape, once both are read. + if "chunk_grid" in read and shape is not None: + problems.extend(chunk_grid_problems(read["chunk_grid"], shape, ("chunk_grid",))) for key, kind in _EXTENSION_LISTS_V3: if key in doc: entries = doc[key] @@ -410,7 +420,6 @@ def validate_array_metadata_v3( # field-level loc, not per-bad-item locs; per-index locs are reserved for # the metadata-field lists (codecs, storage_transformers). names = doc["dimension_names"] - shape = doc.get("shape") if not _is_array(names): problems.append( ValidationProblem(("dimension_names",), "expected a sequence", "invalid_type") @@ -421,7 +430,7 @@ def validate_array_metadata_v3( ("dimension_names",), "expected items of str or None", "invalid_type" ) ) - elif _is_int_sequence(shape) and len(names) != len(shape): + elif shape is not None and len(names) != len(shape): problems.append( ValidationProblem( ("dimension_names",), @@ -474,19 +483,11 @@ def validate_array_metadata_v2(value: object) -> tuple[ValidationProblem, ...]: problems: list[ValidationProblem] = list(_missing_keys(ARRAY_METADATA_REQUIRED_KEYS_V2, doc)) problems.extend(_validate_other_members(doc, ARRAY_METADATA_STANDARD_KEYS_V2)) problems.extend(_check_literal(doc, "zarr_format", 2)) - shape_problems = _validate_dim_sequence(doc, "shape") - chunks_problems = _validate_dim_sequence(doc, "chunks") + shape, shape_problems = _dimension_lengths(doc, "shape") + chunks, chunks_problems = _dimension_lengths(doc, "chunks") problems.extend(shape_problems) problems.extend(chunks_problems) - shape = doc.get("shape") - chunks = doc.get("chunks") - if ( - len(shape_problems) == 0 - and len(chunks_problems) == 0 - and _is_int_sequence(shape) - and _is_int_sequence(chunks) - and len(shape) != len(chunks) - ): + if shape is not None and chunks is not None and len(shape) != len(chunks): problems.append( ValidationProblem( ("chunks",), diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py index 088a141a37..11541520e6 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py @@ -83,8 +83,8 @@ Problems: TypeAlias = tuple[ValidationProblem, ...] -def no_rules(configuration: object) -> Iterator[ValidationProblem]: - """The rules of a definition with none: every well-typed configuration is allowed.""" +def no_rules(*_: object) -> Iterator[ValidationProblem]: + """The rules of a definition with none, of any kind: everything well typed is allowed.""" yield from () @@ -93,13 +93,6 @@ def unchanged(configuration: T) -> T: return configuration -def no_fill_value_rules( - configuration: object, nested: Nested, value: object -) -> Iterator[ValidationProblem]: - """The fill value rules of a data type with none: every fill value of its JSON shape is allowed.""" - yield from () - - class EmptyConfiguration(TypedDict, closed=True): """The configuration of a definition with nothing to configure, written as its bare name.""" @@ -276,7 +269,7 @@ class DataTypeDefinition(Definition[C]): fill_value: object = JSONValue """The JSON shape of a fill value, as an annotation: `Int8FillValue`.""" - fill_value_rules: Callable[[C, Nested, Any], Iterable[ValidationProblem]] = no_fill_value_rules + fill_value_rules: Callable[[C, Nested, Any], Iterable[ValidationProblem]] = no_rules """What the spec disallows in a fill value of that shape, located in it.""" def _refusal(self) -> str | None: @@ -300,7 +293,18 @@ def _fill_value_parser(annotation: object) -> Parser: @dataclass(frozen=True, kw_only=True, slots=True) class ChunkGridDefinition(Definition[C]): - """A chunk grid.""" + """A chunk grid, and the arrays it fits. + + `shape_rules` is what the spec disallows in a grid of this + configuration over an array of a given shape: a dimension with no + chunk length, chunks that fall short of one. It is handed the + configuration, the fields it holds as the scope read them, and the + shape, and locates its problems in the configuration. A grid that + says nothing of the shape fits every one. + """ + + shape_rules: Callable[[C, Nested, tuple[int, ...]], Iterable[ValidationProblem]] = no_rules + """What the spec disallows in this grid over an array of a shape, located in the configuration.""" @dataclass(frozen=True, kw_only=True, slots=True) @@ -703,6 +707,28 @@ def fill_value_problems( return (*problems, *refused) +def chunk_grid_problems( + chunk_grid: Resolved[ChunkGridDefinition[Any]], shape: tuple[int, ...], loc: Loc = () +) -> Problems: + """What is wrong with `chunk_grid`, a chunk grid field a scope read, over an array of `shape`. + + Judged by the grid's shape rules, which locate their problems in the + configuration, under `loc`, where the field sits: a regular grid with + a chunk length for each of two dimensions, over an array of three. A + grid the scope did not read, out of scope or invalid, is left + unjudged. + """ + definition = chunk_grid.definition + configuration = chunk_grid.configuration + if definition is None or configuration is None: + return () + return _ruled( + definition, + lambda: definition.shape_rules(configuration, chunk_grid.nested, shape), + (*loc, "configuration"), + ) + + def resolve( data: object, kind: type[D], context: Context, loc: Loc = () ) -> tuple[Resolved[D], Problems]: @@ -912,11 +938,11 @@ def _replaced(value: JSONValue, path: Loc, new: JSONValue) -> JSONValue: "Unread", "as_kind", "canonicalize", + "chunk_grid_problems", "configuration_of", "fill_value_problems", "kind_of", "named_configuration", - "no_fill_value_rules", "no_rules", "resolve", "spelled", diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/rectilinear.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/rectilinear.py index b685fca83f..744ce540f9 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/rectilinear.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/rectilinear.py @@ -11,7 +11,7 @@ from zarr_metadata._json import ValidationProblem from zarr_metadata._typed_json import Loc -from zarr_metadata.v3._definition import ChunkGridDefinition +from zarr_metadata.v3._definition import ChunkGridDefinition, Nested RECTILINEAR_CHUNK_GRID_NAME: Final = "rectilinear" """The `name` field value of the rectilinear chunk grid.""" @@ -123,11 +123,43 @@ def _canonical( ) +def _shape_rules( + configuration: RectilinearChunkGridConfiguration, nested: Nested, shape: tuple[int, ...] +) -> Iterator[ValidationProblem]: + """Chunk lengths for each of the array's dimensions, which cover it. + + "The length of `chunk_shapes` MUST match the number of dimensions of + the array", and "The sum of the edge lengths MUST equal or exceed `L`" + (https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/chunk-grids/rectilinear/README.md?plain=1#L62-L91). + A bare integer repeats until it covers the dimension, so it always does. + """ + chunk_shapes = configuration["chunk_shapes"] + if len(chunk_shapes) != len(shape): + yield ValidationProblem( + ("chunk_shapes",), + f"expected one chunk_shapes entry per dimension of shape, got {len(chunk_shapes)}", + "invalid_value", + ) + return + for axis, (spec, extent) in enumerate(zip(chunk_shapes, shape, strict=True)): + if isinstance(spec, int): + continue + covered = sum(entry if isinstance(entry, int) else entry[0] * entry[1] for entry in spec) + if covered < extent: + yield ValidationProblem( + ("chunk_shapes", axis), + f"expected chunk lengths that cover the dimension's length {extent}, " + f"got lengths summing to {covered}", + "invalid_value", + ) + + RECTILINEAR_CHUNK_GRID: Final = ChunkGridDefinition( name=RECTILINEAR_CHUNK_GRID_NAME, configuration=RectilinearChunkGridConfiguration, rules=_rules, canonical=_canonical, + shape_rules=_shape_rules, ) """The `rectilinear` chunk grid.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/regular.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/regular.py index c6992888b6..705679b550 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/regular.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_grid/regular.py @@ -10,7 +10,7 @@ from typing_extensions import TypedDict from zarr_metadata._json import ValidationProblem -from zarr_metadata.v3._definition import ChunkGridDefinition +from zarr_metadata.v3._definition import ChunkGridDefinition, Nested REGULAR_CHUNK_GRID_NAME: Final = "regular" """The `name` field value of the regular chunk grid.""" @@ -49,8 +49,8 @@ def _rules(configuration: RegularChunkGridConfiguration) -> Iterator[ValidationP "The chunk shape elements are non-zero when the corresponding dimensions of the arrays have non-zero length": an extent of 0 is right for a dimension of length 0, which zarr-python 3.0 and 3.1 - wrote, and which a grid alone cannot tell from one that is not. The - array's shape can, where the grid is read beside it. + wrote, and which a grid alone cannot tell from one that is not; the + shape rules can, beside the array's shape. """ for index, extent in enumerate(configuration["chunk_shape"]): if extent < 0: @@ -59,8 +59,40 @@ def _rules(configuration: RegularChunkGridConfiguration) -> Iterator[ValidationP ) +def _shape_rules( + configuration: RegularChunkGridConfiguration, nested: Nested, shape: tuple[int, ...] +) -> Iterator[ValidationProblem]: + """A chunk length for each of the array's dimensions, and 0 only for a dimension of length 0. + + "The dimensionality of the grid is the same as the dimensionality of + the array" + (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/chunk-grids/regular-grid/index.rst#L29-L31), + and "The chunk shape elements are non-zero when the corresponding + dimensions of the arrays have non-zero length" + (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/core/index.rst#L284-L285). + """ + chunk_shape = configuration["chunk_shape"] + if len(chunk_shape) != len(shape): + yield ValidationProblem( + ("chunk_shape",), + f"expected one chunk length per dimension of shape, got {len(chunk_shape)}", + "invalid_value", + ) + return + for axis, (length, extent) in enumerate(zip(chunk_shape, shape, strict=True)): + if length == 0 and extent != 0: + yield ValidationProblem( + ("chunk_shape", axis), + f"expected a chunk length >= 1 for a dimension of length {extent}, got 0", + "invalid_value", + ) + + REGULAR_CHUNK_GRID: Final = ChunkGridDefinition( - name=REGULAR_CHUNK_GRID_NAME, configuration=RegularChunkGridConfiguration, rules=_rules + name=REGULAR_CHUNK_GRID_NAME, + configuration=RegularChunkGridConfiguration, + rules=_rules, + shape_rules=_shape_rules, ) """The `regular` chunk grid.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/_numpy_time.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/_numpy_time.py index d9d972284b..9b3b6671d0 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/_numpy_time.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/_numpy_time.py @@ -40,7 +40,7 @@ def numpy_time_fill_value_rules( ) -> Iterator[ValidationProblem]: """An integer fill value is a signed 64-bit one; `"NaT"` is the other form, which the shape admits. - https://github.com/zarr-developers/zarr-extensions/blob/6a3adaeef244b3c76270dca52d6a849e88cf002c/data-types/numpy.datetime64/README.md?plain=1#L109-L112 + https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/data-types/numpy.datetime64/README.md?plain=1#L109-L112 """ if isinstance(value, int) and not -(2**63) <= value <= 2**63 - 1: yield ValidationProblem( diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/struct.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/struct.py index 9e52d59a96..789374158f 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/struct.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/struct.py @@ -96,7 +96,7 @@ def _fill_value_rules( """A fill value for every field, each one judged by that field's own type, and for nothing else. Every field needs one, valid for its type - (https://github.com/zarr-developers/zarr-extensions/blob/6a3adaeef244b3c76270dca52d6a849e88cf002c/data-types/struct/README.md?plain=1#L221-L224). + (https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/data-types/struct/README.md?plain=1#L221-L224). A field type the scope did not read, or whose reading the struct's does not hold, leaves its fill value unjudged. """ diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/definition.py b/packages/zarr-metadata/src/zarr_metadata/v3/definition.py index 07a84e05b7..92623a04b8 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/definition.py @@ -110,9 +110,10 @@ def acme_lz4_rules(configuration: AcmeLz4Configuration) -> Iterator[ValidationPr `validate_array_metadata_v3(document, context=SCOPE)`, from `zarr_metadata.model`, reads each extension point of a v3 array document through the definitions in `SCOPE`, and so do the model's `from_json` and -`from_key_value`, and a fill value is judged against the data type it -names, by that data type's definition. No rule here reads a codec against -the array it is handed, or a chunk grid against the shape. +`from_key_value`: a fill value is judged against the data type it names, +by that data type's definition, and the chunk grid against the shape, by +the grid's definition. No rule here reads a codec against the array it +is handed. The TypedDict says what a key it does not declare is: with `closed=True`, a problem, as above; with `extra_items=`, a key holding @@ -147,6 +148,12 @@ def acme_lz4_rules(configuration: AcmeLz4Configuration) -> Iterator[ValidationPr type field the scope read; one nothing in scope claims leaves it unjudged. A data type that says nothing of its fill value takes any JSON. +A chunk grid says which arrays it fits: `shape_rules`, a function +yielding what the spec disallows in a grid of its configuration over an +array of a given shape -- a dimension with no chunk length, chunks that +fall short of one -- located in the configuration. A grid that says +nothing of the shape fits every one. + Raw bits are the one data type whose name carries its configuration: a document writes `r` and the size in bits, and `r16` reads as `r*`, as the specification's table writes raw bits, with `{"bits": 16}`. A reader that @@ -169,11 +176,12 @@ def acme_lz4_rules(configuration: AcmeLz4Configuration) -> Iterator[ValidationPr `TypeError` saying what is wrong: a `configuration` that is not a TypedDict, says nothing of the keys it does not declare, or has a member no checker reads, named down to the TypedDict that holds it; a `name` -that is not a string; `rules` or `canonical` that are not functions; a -codec `kind` that is not one of the three, or a `size` that is not -`"static"` or `"dynamic"`; a data type named as raw bits of one size are -written. A scope refuses a definition of no kind. Nothing happens at -class creation. +that is not a string; a member declared as a function -- `rules`, +`canonical`, `fill_value_rules`, `shape_rules` -- that is not one; a data +type's `fill_value` no checker reads; a codec `kind` that is not one of +the three, or a `size` that is not `"static"` or `"dynamic"`; a data type +named as raw bits of one size are written. A scope refuses a definition +of no kind. Nothing happens at class creation. """ from zarr_metadata._common import JSONValue diff --git a/packages/zarr-metadata/tests/model/test_array.py b/packages/zarr-metadata/tests/model/test_array.py index a07bfa1c76..6db6bfa3d5 100644 --- a/packages/zarr-metadata/tests/model/test_array.py +++ b/packages/zarr-metadata/tests/model/test_array.py @@ -1572,7 +1572,8 @@ def test_error_array_v2_key_that_is_not_a_string(key: object) -> None: def test_array_v3_from_json_materializes_abstract_containers() -> None: """A flexible input mapping becomes the canonical dict/tuple model shape.""" - doc = UserDict(dict(ZarrV3ArrayMetadata.create_default(shape=(2,)).to_json())) + # `range(2)` is the shape (0, 1), which the default grid for it fits. + doc = UserDict(dict(ZarrV3ArrayMetadata.create_default(shape=(0, 1)).to_json())) doc["shape"] = range(2) model = ZarrV3ArrayMetadata.from_json(doc) diff --git a/packages/zarr-metadata/tests/v3/test_definitions.py b/packages/zarr-metadata/tests/v3/test_definitions.py index bd56034d83..4c5babfe2f 100644 --- a/packages/zarr-metadata/tests/v3/test_definitions.py +++ b/packages/zarr-metadata/tests/v3/test_definitions.py @@ -710,11 +710,21 @@ def test_error_a_data_type_fill_value_no_checker_reads() -> None: DataTypeDefinition(name="acme.set", configuration=Empty, fill_value=set[int]) -@pytest.mark.parametrize("member", ["rules", "canonical", "fill_value_rules"]) -def test_error_a_function_member_that_is_not_a_function(member: str) -> None: +@pytest.mark.parametrize( + ("kind", "member"), + [ + (DataTypeDefinition, "rules"), + (DataTypeDefinition, "canonical"), + (DataTypeDefinition, "fill_value_rules"), + (ChunkGridDefinition, "shape_rules"), + ], +) +def test_error_a_function_member_that_is_not_a_function( + kind: type[Definition[Any]], member: str +) -> None: # Each member a definition's annotations declare a `Callable`. with pytest.raises(TypeError, match=f"'acme.t': {member} is a function, got 'none'"): - DataTypeDefinition(name="acme.t", configuration=Empty, **{member: "none"}) # pyright: ignore[reportArgumentType] + kind(name="acme.t", configuration=Empty, **{member: "none"}) # pyright: ignore[reportArgumentType] @pytest.mark.parametrize("kind", [Definition, AcmeCodecDefinition]) diff --git a/packages/zarr-metadata/tests/v3/test_grid_shapes.py b/packages/zarr-metadata/tests/v3/test_grid_shapes.py new file mode 100644 index 0000000000..dc98c18018 --- /dev/null +++ b/packages/zarr-metadata/tests/v3/test_grid_shapes.py @@ -0,0 +1,117 @@ +"""Chunk grids, judged against the shape of the array they chunk. + +Each grid's definition says what the spec disallows in a grid of its +configuration over an array of a given shape; `chunk_grid_problems` +judges a grid field a scope read, and the v3 array validators judge a +document's `chunk_grid` against its `shape`. +""" + +from __future__ import annotations + +import pytest + +from zarr_metadata.model import ZarrV3ArrayMetadata, validate_array_metadata_v3 +from zarr_metadata.v3._definition import chunk_grid_problems +from zarr_metadata.v3.codec.crc32c import Empty +from zarr_metadata.v3.definition import ( + CORE_AND_EXTENSIONS, + ChunkGridDefinition, + JSONValue, + resolve, +) + + +def _regular(*lengths: int) -> JSONValue: + return {"name": "regular", "configuration": {"chunk_shape": list(lengths)}} + + +def _rectilinear(*specs: JSONValue) -> JSONValue: + return {"name": "rectilinear", "configuration": {"kind": "inline", "chunk_shapes": list(specs)}} + + +def _problems(grid: JSONValue, shape: tuple[int, ...]) -> list[tuple[tuple[str | int, ...], str]]: + resolved, found = resolve(grid, ChunkGridDefinition, CORE_AND_EXTENSIONS) + assert found == () + return [(problem.loc, problem.kind) for problem in chunk_grid_problems(resolved, shape)] + + +@pytest.mark.parametrize( + ("grid", "shape"), + [ + (_regular(), ()), + (_regular(4, 4), (10, 3)), + # A chunk longer than its dimension, and a chunk length of 0 for a + # dimension of length 0. + (_regular(8, 0), (3, 0)), + # A bare integer repeats until it covers its dimension. + (_rectilinear(4), (10,)), + (_rectilinear([4, 4, 2]), (10,)), + # Overflowing the dimension is allowed. + (_rectilinear([4, 4, 4]), (10,)), + (_rectilinear([[4, 2], 2]), (10,)), + # Nothing to cover. + (_rectilinear([]), (0,)), + (_rectilinear(2, [3, 3]), (7, 6)), + # A grid nothing in scope claims, or one that is not read, is left + # unjudged. + ({"name": "acme.grid", "configuration": {"x": 1}}, (3,)), + (_regular(-1), (3,)), + ], +) +def test_every_chunk_grid_fits_the_shapes_it_covers( + grid: JSONValue, shape: tuple[int, ...] +) -> None: + resolved, _ = resolve(grid, ChunkGridDefinition, CORE_AND_EXTENSIONS) + assert chunk_grid_problems(resolved, shape) == () + + +@pytest.mark.parametrize( + ("grid", "shape"), [(_regular(4), (10, 3)), (_regular(4, 4), ()), (_regular(), (1,))] +) +def test_error_a_regular_grid_of_another_rank(grid: JSONValue, shape: tuple[int, ...]) -> None: + assert _problems(grid, shape) == [(("configuration", "chunk_shape"), "invalid_value")] + + +def test_error_a_regular_chunk_length_of_0_for_a_dimension_that_is_not_empty() -> None: + assert _problems(_regular(4, 0), (4, 3)) == [ + (("configuration", "chunk_shape", 1), "invalid_value") + ] + + +@pytest.mark.parametrize( + ("grid", "shape"), [(_rectilinear(4), (10, 3)), (_rectilinear(4, 4), (1,))] +) +def test_error_a_rectilinear_grid_of_another_rank(grid: JSONValue, shape: tuple[int, ...]) -> None: + assert _problems(grid, shape) == [(("configuration", "chunk_shapes"), "invalid_value")] + + +@pytest.mark.parametrize("spec", [[4, 4], [[4, 2]], []]) +def test_error_rectilinear_chunks_that_do_not_cover_their_dimension(spec: JSONValue) -> None: + assert _problems(_rectilinear(2, spec), (4, 10)) == [ + (("configuration", "chunk_shapes", 1), "invalid_value") + ] + + +def test_a_grid_without_shape_rules_fits_every_shape() -> None: + lenient = ChunkGridDefinition(name="acme.grid", configuration=Empty) + scope = CORE_AND_EXTENSIONS.extended_with(lenient) + resolved, _ = resolve("acme.grid", ChunkGridDefinition, scope) + assert chunk_grid_problems(resolved, (3, 4)) == () + + +def test_error_an_array_document_s_chunk_grid_that_does_not_fit_its_shape() -> None: + # Located in the document's grid. + document = dict(ZarrV3ArrayMetadata.create_default(shape=(4, 4)).to_json()) + document["chunk_grid"] = _regular(4) + assert [(p.loc, p.kind) for p in validate_array_metadata_v3(document)] == [ + (("chunk_grid", "configuration", "chunk_shape"), "invalid_value") + ] + + +def test_error_an_array_document_s_shape_that_is_not_read_leaves_its_grid_unjudged() -> None: + document = dict(ZarrV3ArrayMetadata.create_default(shape=(4, 4)).to_json()) + document["chunk_grid"] = _regular(4) + document["shape"] = (4, -1) + assert [(p.loc, p.kind) for p in validate_array_metadata_v3(document)] == [ + (("shape",), "invalid_value") + ] From a0510ff165a9e6070106b4982ec6464ec35b1687 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 27 Sep 2026 17:22:57 +0200 Subject: [PATCH 2/3] fix(zarr-metadata): create_default gives an empty dimension a chunk length of 1 The grid `create_default` derives from an overridden `shape` had a chunk length of 0 for a dimension of length 0. The regular grid asks for chunk lengths greater than zero, and `zarr` refuses to open such a grid, so the derived grid now has a chunk length of 1 there. It still fits the shape. Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-metadata/changes/+layer-4b.bugfix.md | 3 +++ .../zarr-metadata/src/zarr_metadata/model/_array.py | 7 +++++-- packages/zarr-metadata/tests/model/test_array.py | 10 +++++----- 3 files changed, 13 insertions(+), 7 deletions(-) create mode 100644 packages/zarr-metadata/changes/+layer-4b.bugfix.md diff --git a/packages/zarr-metadata/changes/+layer-4b.bugfix.md b/packages/zarr-metadata/changes/+layer-4b.bugfix.md new file mode 100644 index 0000000000..645f8ec603 --- /dev/null +++ b/packages/zarr-metadata/changes/+layer-4b.bugfix.md @@ -0,0 +1,3 @@ +`ZarrV3ArrayMetadata.create_default(shape=...)` derives a chunk length of 1 +for a dimension of length 0, where it wrote 0: the regular grid asks for +chunk lengths greater than zero, and `zarr` does not open a grid with one. diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_array.py b/packages/zarr-metadata/src/zarr_metadata/model/_array.py index 6161d34eb2..4d5140eea0 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_array.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_array.py @@ -191,7 +191,9 @@ def create_default(cls, **overrides: Unpack[ZarrV3ArrayMetadataPartial]) -> Zarr analog of `list()` returning `[]`. Any field can be overridden by keyword (the same fields accepted by `update`). Overriding `shape` without `chunk_grid` derives a consistent default grid: one regular chunk - covering the array (`chunk_shape` equal to `shape`). + covering the array (`chunk_shape` equal to `shape`, with a length of + 1 for a dimension of length 0, since a chunk length is at least 1: + https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/chunk-grids/regular-grid/index.rst#L40). The derivation is deliberately one-way. A user-supplied `chunk_grid` is an extension point and is taken verbatim — deriving `shape` from @@ -206,8 +208,9 @@ def create_default(cls, **overrides: Unpack[ZarrV3ArrayMetadataPartial]) -> Zarr refuses, so pass the two together. """ if "shape" in overrides and "chunk_grid" not in overrides: + chunk_shape = tuple(max(length, 1) for length in overrides["shape"]) overrides["chunk_grid"] = ZarrV3NamedConfig( - name="regular", configuration={"chunk_shape": tuple(overrides["shape"])} + name="regular", configuration={"chunk_shape": chunk_shape} ) default = cls( shape=(), diff --git a/packages/zarr-metadata/tests/model/test_array.py b/packages/zarr-metadata/tests/model/test_array.py index 6db6bfa3d5..17f81fc13f 100644 --- a/packages/zarr-metadata/tests/model/test_array.py +++ b/packages/zarr-metadata/tests/model/test_array.py @@ -1893,12 +1893,12 @@ def test_v2_create_default_explicit_chunks_respected() -> None: def test_v3_create_default_zero_length_dimensions() -> None: - """chunk_shape == shape is spec-sound even with zero-length dimensions: - 'The chunk shape elements are non-zero when the corresponding dimensions - of the arrays have non-zero length' — the constraint is conditional, so a - zero chunk length is permitted exactly where the dimension is empty.""" + """The derived grid gives a dimension of length 0 a chunk length of 1: + the regular grid asks for chunk sizes greater than zero, so the written + grid is one every reader takes, and it fits the shape it chunks.""" model = ZarrV3ArrayMetadata.create_default(shape=(0, 3)) - assert model.chunk_grid.configuration["chunk_shape"] == (0, 3) + assert model.chunk_grid.configuration["chunk_shape"] == (1, 3) + assert validate_array_metadata_v3(model.to_json()) == () def test_create_default_derivation_is_one_way() -> None: From 73f539873ff4b54b6b361d35a52dc15933cb750a Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Sun, 27 Sep 2026 17:25:57 +0200 Subject: [PATCH 3/3] docs(zarr-metadata): the grid fragments take this PR's number Assisted-by: ClaudeCode:claude-opus-5-5 --- .../zarr-metadata/changes/{+layer-4b.bugfix.md => 367.bugfix.md} | 0 .../changes/{+layer-4b.feature.md => 367.feature.md} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename packages/zarr-metadata/changes/{+layer-4b.bugfix.md => 367.bugfix.md} (100%) rename packages/zarr-metadata/changes/{+layer-4b.feature.md => 367.feature.md} (100%) diff --git a/packages/zarr-metadata/changes/+layer-4b.bugfix.md b/packages/zarr-metadata/changes/367.bugfix.md similarity index 100% rename from packages/zarr-metadata/changes/+layer-4b.bugfix.md rename to packages/zarr-metadata/changes/367.bugfix.md diff --git a/packages/zarr-metadata/changes/+layer-4b.feature.md b/packages/zarr-metadata/changes/367.feature.md similarity index 100% rename from packages/zarr-metadata/changes/+layer-4b.feature.md rename to packages/zarr-metadata/changes/367.feature.md