diff --git a/packages/zarr-metadata/README.md b/packages/zarr-metadata/README.md index ed4a4783cd..75bae98677 100644 --- a/packages/zarr-metadata/README.md +++ b/packages/zarr-metadata/README.md @@ -128,11 +128,21 @@ metadata = reading.metadata # None when reading.problems is not empty its consolidated metadata holds once. `read_node_metadata_v3` reads a `zarr.json` of either kind as the node its `node_type` says it is, as a discriminated union reads its tag: a document that says neither reads -as `ZarrV3UnknownNodeReading`, with the problem, and nothing else of it -is read. `node_metadata_from_json_v3` and `node_metadata_from_key_value_v3` +as `ZarrV3UnknownNodeReading`, with the problems, and nothing else of it +is read but its `zarr_format`, so a document of another format says it +is not v3. `node_metadata_from_json_v3` and `node_metadata_from_key_value_v3` build the model of either kind, as the models' own `from_json` and `from_key_value` build one. +Consolidated metadata holds the hierarchy below its group, the group its +root: the document of the node at `/a/b` sits at the key `a/b`, and the +documents and the group make a tree in which only groups hold nodes and +each node's parent is held. `NodeName` and `NodePath`, in +`zarr_metadata.v3`, are the strings the spec's rules for node names and +paths hold of, modelled on zarrs' types of those names, and +`validate_node_name_v3`, `is_node_name_v3` and `parse_node_name_v3`, and +their `node_path` twins, judge a string by them. + A member the spec does not define is not a field; the model's `must_understand_fields` names those a reader must understand. @@ -148,6 +158,20 @@ read. A model a read builds is not read a second time. Change a model by building another: a container it holds, changed in place, is not checked again. +Two models are equal when they mean the same document, however each is +spelled. What the package interprets -- each field, and the fill value +against its data type -- compares by its canonical spelling, as +`canonical_of` and `canonical_fill_value` give it: `"NaN"` and +`"0x7fc00000"` are one `float32` fill value, `0.0` and `-0.0` two, and a +blosc with and without the `typesize` that `noshuffle` ignores one +codec. What it does not interpret -- attributes, extra fields, the +configuration of a field nothing in scope claims, and every member of a +v2 document -- compares as JSON text, which tells `true` from `1` and +`-0.0` from `0.0`, and takes `NaN` for itself. Equal models hash alike, +and may write two documents: `to_json` writes each as it was given. A +model's hash is of what its containers held when it was hashed, so a +model in a set, or a key of a dict, is not changed in place. + `node_metadata_json_schema_v3` writes what the validators read as a JSON Schema, draft 2020-12, for an editor that checks a `zarr.json` as it is written, or a validator in another language. Each extension point is diff --git a/packages/zarr-metadata/changes/381.bugfix.1.md b/packages/zarr-metadata/changes/381.bugfix.1.md new file mode 100644 index 0000000000..6bfaeb669a --- /dev/null +++ b/packages/zarr-metadata/changes/381.bugfix.1.md @@ -0,0 +1,6 @@ +A `zarr.json` that says no node type the spec defines is judged by its +`zarr_format` too, so a document of another format says it is not v3. +The root `zarr.json` of zarr-python 2's draft of v3, whose `zarr_format` +is a URL, was reported only as missing its `node_type`; it now also has +an `invalid_type` problem at `zarr_format`, and a v2 document read as a +`zarr.json` an `invalid_value` there. diff --git a/packages/zarr-metadata/changes/381.bugfix.2.md b/packages/zarr-metadata/changes/381.bugfix.2.md new file mode 100644 index 0000000000..9c5b0f86bb --- /dev/null +++ b/packages/zarr-metadata/changes/381.bugfix.2.md @@ -0,0 +1,9 @@ +A group's consolidated metadata is judged as the hierarchy below the +group, the group its root: zarr-python keeps the document of the node at +`/a/b` at the key `a/b`, and the documents and the group make a tree in +which only groups hold nodes and each node's parent is held. A key that +is no node's path below the group, such as `""`, `"__a"` or `"a/../b"`, +and a document below an array's were read without a problem, and so was +a document whose group is missing, which zarr-python fails to read. Each +is a problem now, a missing group a `missing_key`, and +`ZarrV3ConsolidatedMetadata` refuses them when it is built. diff --git a/packages/zarr-metadata/changes/381.bugfix.3.md b/packages/zarr-metadata/changes/381.bugfix.3.md new file mode 100644 index 0000000000..bc3f7ef3ed --- /dev/null +++ b/packages/zarr-metadata/changes/381.bugfix.3.md @@ -0,0 +1,14 @@ +Two models are equal when they mean the same document, however each is +spelled. What the package interprets compares by its canonical spelling: +`"NaN"` and `"0x7fc00000"` were two `float32` fill values and `0.0` and +`-0.0` one, and a blosc with and without the `typesize` that `noshuffle` +ignores, a key encoding with and without its default separator, a shard +with and without `index_location: "end"` and a zstd with and without +`checksum: false` were two fields each, though `canonical_of` spelled +them alike; each is one now, and `default`, `v2`, `sharding_indexed` +and `zstd` fold their spec defaults in a `canonical` of their own. What +it does not interpret -- attributes, extra fields, unclaimed +configurations, every member of a v2 document -- compares as JSON text, +which tells `true` from `1` and `-0.0` from `0.0` and takes `NaN` for +itself, so a model holding a NaN attribute equals its own copy. Equal +fields and models hash alike. diff --git a/packages/zarr-metadata/changes/381.bugfix.md b/packages/zarr-metadata/changes/381.bugfix.md new file mode 100644 index 0000000000..5b3ebacb69 --- /dev/null +++ b/packages/zarr-metadata/changes/381.bugfix.md @@ -0,0 +1,9 @@ +A member a closed object does not declare is an `unknown_key` wherever +it sits, as `ProblemKind` defines one: in a v2 `.zgroup`, a `.zmetadata` +envelope, a group's `consolidated_metadata` and a metadata field's +envelope, where it was an `invalid_value`, as it already was inside a v3 +configuration. So a reader that tolerates a key another writer added, +such as netCDF-C's `_nczarr_*` keys in a `.zgroup`, can filter by kind. +A definition's `check` and `judge` give a configuration back when a +field it holds has a stray member, which they report and leave out, as +the checker does a key a closed TypedDict does not declare. diff --git a/packages/zarr-metadata/changes/381.feature.1.md b/packages/zarr-metadata/changes/381.feature.1.md new file mode 100644 index 0000000000..48a0348c8b --- /dev/null +++ b/packages/zarr-metadata/changes/381.feature.1.md @@ -0,0 +1,10 @@ +A data type's definition says which spelling of a fill value is its +value's own: `DataTypeDefinition.fill_value_canonical`, and +`canonical_fill_value(data_type, value)` in `zarr_metadata.v3.definition` +spells one, or gives `UNSET` for a fill value with a problem. The float +types read a number as a float64, as JSON parsers and numpy do, and +spell a value by its shortest number, a named value, or the bits of a +NaN the spec does not name; the complex types spell each part so; the +numpy time types spell `-2**63` as `"NaT"`; `bytes` spells its bytes as +base64; and a struct spells each field's fill value by that field's +type. diff --git a/packages/zarr-metadata/changes/381.feature.md b/packages/zarr-metadata/changes/381.feature.md new file mode 100644 index 0000000000..a526471296 --- /dev/null +++ b/packages/zarr-metadata/changes/381.feature.md @@ -0,0 +1,5 @@ +`NodeName` and `NodePath`, in `zarr_metadata.v3`, are the names and paths +of the nodes of a v3 hierarchy, modelled on zarrs' types of those names, +and `zarr_metadata.model` judges a string by the spec's rules for them: +`validate_node_name_v3`, `is_node_name_v3` and `parse_node_name_v3`, and +their `node_path` twins. diff --git a/packages/zarr-metadata/docs/api/v3/index.md b/packages/zarr-metadata/docs/api/v3/index.md index f20267d372..b0f5c2ab4e 100644 --- a/packages/zarr-metadata/docs/api/v3/index.md +++ b/packages/zarr-metadata/docs/api/v3/index.md @@ -8,6 +8,10 @@ title: v3 ::: zarr_metadata.v3.ZarrV3MetadataFieldJSON +::: zarr_metadata.v3.NodeName + +::: zarr_metadata.v3.NodePath + ::: zarr_metadata.v3.array ::: zarr_metadata.v3.group diff --git a/packages/zarr-metadata/docs/index.md b/packages/zarr-metadata/docs/index.md index 70608414dd..7e99d31144 100644 --- a/packages/zarr-metadata/docs/index.md +++ b/packages/zarr-metadata/docs/index.md @@ -143,11 +143,21 @@ metadata = reading.metadata # None when reading.problems is not empty its consolidated metadata holds once. `read_node_metadata_v3` reads a `zarr.json` of either kind as the node its `node_type` says it is, as a discriminated union reads its tag: a document that says neither reads -as `ZarrV3UnknownNodeReading`, with the problem, and nothing else of it -is read. `node_metadata_from_json_v3` and `node_metadata_from_key_value_v3` +as `ZarrV3UnknownNodeReading`, with the problems, and nothing else of it +is read but its `zarr_format`, so a document of another format says it +is not v3. `node_metadata_from_json_v3` and `node_metadata_from_key_value_v3` build the model of either kind, as the models' own `from_json` and `from_key_value` build one. +Consolidated metadata holds the hierarchy below its group, the group its +root: the document of the node at `/a/b` sits at the key `a/b`, and the +documents and the group make a tree in which only groups hold nodes and +each node's parent is held. `NodeName` and `NodePath`, in +`zarr_metadata.v3`, are the strings the spec's rules for node names and +paths hold of, modelled on zarrs' types of those names, and +`validate_node_name_v3`, `is_node_name_v3` and `parse_node_name_v3`, and +their `node_path` twins, judge a string by them. + A member the spec does not define is not a field; the model's `must_understand_fields` names those a reader must understand. @@ -163,6 +173,20 @@ read. A model a read builds is not read a second time. Change a model by building another: a container it holds, changed in place, is not checked again. +Two models are equal when they mean the same document, however each is +spelled. What the package interprets -- each field, and the fill value +against its data type -- compares by its canonical spelling, as +`canonical_of` and `canonical_fill_value` give it: `"NaN"` and +`"0x7fc00000"` are one `float32` fill value, `0.0` and `-0.0` two, and a +blosc with and without the `typesize` that `noshuffle` ignores one +codec. What it does not interpret -- attributes, extra fields, the +configuration of a field nothing in scope claims, and every member of a +v2 document -- compares as JSON text, which tells `true` from `1` and +`-0.0` from `0.0`, and takes `NaN` for itself. Equal models hash alike, +and may write two documents: `to_json` writes each as it was given. A +model's hash is of what its containers held when it was hashed, so a +model in a set, or a key of a dict, is not changed in place. + `node_metadata_json_schema_v3` writes what the validators read as a JSON Schema, draft 2020-12, for an editor that checks a `zarr.json` as it is written, or a validator in another language. Each extension point is diff --git a/packages/zarr-metadata/src/zarr_metadata/_json.py b/packages/zarr-metadata/src/zarr_metadata/_json.py index 99c66e5b5c..de7ac9b92c 100644 --- a/packages/zarr-metadata/src/zarr_metadata/_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/_json.py @@ -334,6 +334,16 @@ def _refine(value: object, loc: tuple[str | int, ...], *, finite: bool) -> _Refi ) +def json_text(value: JSONValue) -> str: + """`value` as the JSON text `json.dumps` writes for it, an object's keys sorted: what `==` compares of a JSON value the package does not interpret. + + Not Python's `==` on the value, which takes `true` for `1`, `-0.0` for + `0.0` and `NaN` for no value at all, but what a document writes: two + values written alike are one value to every reader. + """ + return json.dumps(value, sort_keys=True, ensure_ascii=False) + + def shown(value: object) -> str: """`value` as a problem's message shows it: as the JSON a document writes, `null` and `[1, 2]`, or by its repr when it is not JSON.""" refined, problems = _refine(value, (), finite=False) diff --git a/packages/zarr-metadata/src/zarr_metadata/model/__init__.py b/packages/zarr-metadata/src/zarr_metadata/model/__init__.py index ad74f9f072..f967996b82 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/__init__.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/__init__.py @@ -106,6 +106,14 @@ parse_metadata_field_v3, validate_metadata_field_v3, ) +from zarr_metadata.v3._hierarchy import ( + is_node_name_v3, + is_node_path_v3, + parse_node_name_v3, + parse_node_path_v3, + validate_node_name_v3, + validate_node_path_v3, +) from zarr_metadata.v3.array import ( ZARR_V3_ARRAY_METADATA_STORE_KEY, ZarrV3ArrayMetadataStoreKey, @@ -163,6 +171,8 @@ "is_group_metadata_v3", "is_json", "is_metadata_field_v3", + "is_node_name_v3", + "is_node_path_v3", "node_metadata_from_json_v3", "node_metadata_from_key_value_v3", "node_metadata_json_schema_v3", @@ -172,6 +182,8 @@ "parse_group_metadata_v3", "parse_json", "parse_metadata_field_v3", + "parse_node_name_v3", + "parse_node_path_v3", "read_array_metadata_v3", "read_group_metadata_v3", "read_node_metadata_v3", @@ -182,4 +194,6 @@ "validate_json", "validate_metadata_field_v3", "validate_node_metadata_v3", + "validate_node_name_v3", + "validate_node_path_v3", ] diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_array.py b/packages/zarr-metadata/src/zarr_metadata/model/_array.py index 20f743471a..9c65362e5e 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_array.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_array.py @@ -14,6 +14,7 @@ MetadataValidationError, ValidationProblem, copied, + json_text, with_input, ) from zarr_metadata._sentinel import UNSET @@ -42,6 +43,8 @@ StorageTransformerDefinition, Unclaimed, document_json, + field_key, + spelled_canonically, ) from zarr_metadata.v3._registry import CORE_AND_EXTENSIONS, Context from zarr_metadata.v3.array import ZARR_V3_ARRAY_METADATA_STORE_KEY, ZarrV3ExtensionField @@ -231,6 +234,27 @@ def __post_init__(self) -> None: object.__setattr__(self, "codecs", tuple(self.codecs)) object.__setattr__(self, "storage_transformers", tuple(self.storage_transformers)) + def __eq__(self, other: object) -> bool: + """Whether `other` models the same array: the same document, however each is spelled. + + Compared as `array_key` says: what the package interprets -- each + field, and the fill value against the data type -- in its canonical + spelling, so `"NaN"` and `"0x7fc00000"` are one `float32` fill value + and a blosc with and without the `typesize` that `noshuffle` ignores + one codec; and what it does not interpret -- the attributes, the + extra fields, the fill value of a data type nothing in scope claims + -- as JSON text, which tells `true` from `1` and `-0.0` from `0.0`, + and takes `NaN` for itself. So two equal models may write two + documents: `to_json` writes each as it was given. Equal models hash + alike. + """ + if type(other) is not type(self): + return NotImplemented + return array_key(self) == array_key(cast("ZarrV3ArrayMetadata", other)) + + def __hash__(self) -> int: + return hash(array_key(self)) + def to_json(self) -> ZarrV3ArrayMetadataJSON: """The document as JSON, arrays as tuples, sharing no mutable state with the model. @@ -293,6 +317,34 @@ def to_key_value( return {ZARR_V3_ARRAY_METADATA_STORE_KEY: dump_store_json(array_json(self), indent=indent)} +def array_key(model: ZarrV3ArrayMetadata) -> tuple[object, ...]: + """What `==` and `hash` compare of a v3 array model: what its document means. + + Each field by its `field_key`, the fill value in its canonical spelling + as JSON text when a definition in scope read the data type, and every + other member as it is, the JSON ones as text. + """ + return ( + model.shape, + _fill_value_key(model), + field_key(model.data_type), + field_key(model.chunk_grid), + tuple(field_key(codec) for codec in model.codecs), + field_key(model.chunk_key_encoding), + model.dimension_names, + json_text(model.attributes), + tuple(field_key(transformer) for transformer in model.storage_transformers), + json_text(model.extra_fields), + ) + + +def _fill_value_key(model: ZarrV3ArrayMetadata) -> str: + """What `==` compares of `model`'s fill value: its canonical spelling as JSON text when a definition in scope read the data type, and the fill value as written when none did.""" + if isinstance(model.data_type, Read): + return json_text(spelled_canonically(model.data_type, model.fill_value)) + return json_text(model.fill_value) + + def _members(model: ZarrV3ArrayMetadata) -> ArrayMembersV3: """`model`'s members other than its fields, as the read of its document by its own fields refines them; `MetadataValidationError` with every problem that document has.""" reading, members = read_array_v3(held_document(model), NO_SCOPE) @@ -506,6 +558,20 @@ def create_default(cls, **overrides: Unpack[ZarrV2ArrayMetadataPartial]) -> Zarr ) return default.update(**overrides) + def __eq__(self, other: object) -> bool: + """Whether `other` models the same array: the same document, as JSON text. + + Nothing in a v2 document is interpreted, so two models are one when + their documents are written alike, which tells `0` from `0.0` and + `-0.0`, and takes `NaN` for itself. Equal models hash alike. + """ + if type(other) is not type(self): + return NotImplemented + return json_text(self.to_json()) == json_text(cast("ZarrV2ArrayMetadata", other).to_json()) + + def __hash__(self) -> int: + return hash(json_text(self.to_json())) + def to_json(self) -> ZarrV2ArrayMetadataJSON: """Return the merged in-memory document form. diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_group.py b/packages/zarr-metadata/src/zarr_metadata/model/_group.py index e9434b925c..ff900f4062 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_group.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_group.py @@ -6,7 +6,7 @@ import dataclasses from collections.abc import Callable, Mapping from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Final, Literal, TypeGuard, cast +from typing import TYPE_CHECKING, Any, Final, Literal, TypeGuard, TypeVar, cast from typing_extensions import TypeAliasType, TypedDict, Unpack @@ -16,10 +16,12 @@ arrays_to_tuples, copied, is_canonical_json, + json_text, not_an_object, outside_of, refine_json, refine_user_data, + shown, with_input, ) from zarr_metadata._json import prefixed as _prefix @@ -27,6 +29,7 @@ from zarr_metadata.model._array import ( ZarrV3ArrayMetadata, array_json, + array_key, array_model, must_understand_subset, read_array_metadata_v3, @@ -53,6 +56,7 @@ from zarr_metadata.v2.attributes import ZARR_V2_ATTRIBUTES_STORE_KEY from zarr_metadata.v2.consolidated import ZARR_V2_CONSOLIDATED_METADATA_STORE_KEY from zarr_metadata.v2.group import ZARR_V2_GROUP_METADATA_STORE_KEY +from zarr_metadata.v3._hierarchy import NodeType, hierarchy_problems, path_faults, said from zarr_metadata.v3._registry import CORE_AND_EXTENSIONS, Context from zarr_metadata.v3.array import ZarrV3ExtensionField from zarr_metadata.v3.consolidated import ZARR_V3_CONSOLIDATED_METADATA_KEY @@ -155,6 +159,15 @@ def update( return updated return dataclasses.replace(updated, consolidated_metadata=self.consolidated_metadata) + def __eq__(self, other: object) -> bool: + """Whether `other` models the same group: the same document, however each is spelled, as `group_key` says; equal models hash alike.""" + if type(other) is not type(self): + return NotImplemented + return group_key(self) == group_key(cast("ZarrV3GroupMetadata", other)) + + def __hash__(self) -> int: + return hash(group_key(self)) + def to_json(self) -> ZarrV3GroupMetadataJSON: """The document as JSON, sharing no mutable state with the model. @@ -226,6 +239,9 @@ class ZarrV3ConsolidatedMetadata: `must_understand` is typed permissively as `bool` to mirror the document shape, but only `False` is valid; this is enforced at runtime. Each document it holds is a model, which checked itself when it was built. + The documents and the group make the hierarchy below the group, the + group its root, each at its node's path in it without the leading `/`: + the node at `/a/b` at `a/b`. """ kind: Literal["inline"] = field(default="inline", init=False) @@ -252,8 +268,34 @@ def __post_init__(self) -> None: if not isinstance(node, (ZarrV3ArrayMetadata, ZarrV3GroupMetadata)): msg = f"metadata[{path!r}]: expected a v3 array or group model, got {node!r}" raise TypeError(msg) + problems: list[ValidationProblem] = [] + node_types: dict[str, NodeType | None] = {} + for path, node in self.metadata.items(): + faults = _key_problems(path) + problems.extend(faults) + if len(faults) == 0: + node_types[path] = _model_node_type(node) + problems.extend(_hierarchy_problems(node_types)) + for path, node in self.metadata.items(): + if path in node_types: + problems.extend( + _nested_listing_problems( + path, _model_listing(node), node_types, _model_node_type + ) + ) + if len(problems) != 0: + raise MetadataValidationError(problems) object.__setattr__(self, "metadata", dict(self.metadata)) + def __eq__(self, other: object) -> bool: + """Whether `other` holds the same documents at the same paths, each as its model compares; equal ones hash alike.""" + if type(other) is not type(self): + return NotImplemented + return consolidated_key(self) == consolidated_key(cast("ZarrV3ConsolidatedMetadata", other)) + + def __hash__(self) -> int: + return hash(consolidated_key(self)) + def to_json(self) -> ZarrV3ConsolidatedMetadataJSON: """The `consolidated_metadata` member as JSON, sharing no mutable state with the model: its `kind`, `must_understand: false`, and each document by its path.""" return cast( @@ -364,7 +406,12 @@ def fields(self) -> Iterator[tuple[Loc, Resolved[Any]]]: @dataclass(frozen=True, slots=True) class ZarrV3UnknownNodeReading: - """A v3 document of no node type the spec defines -- its `node_type` missing, or neither `"array"` nor `"group"` -- or not an object at all: nothing else of it is read, as its problem says.""" + """A v3 document of no node type the spec defines -- its `node_type` missing, or neither `"array"` nor `"group"` -- or not an object at all: nothing else of it is read but its `zarr_format`, as its problems say. + + So a document of another format says so: zarr-python 2's draft of v3 + wrote a root `zarr.json` whose `zarr_format` is a URL, and a v2 + document names format 2. + """ problems: tuple[ValidationProblem, ...] """Why it is no node.""" @@ -395,8 +442,9 @@ def read_node_metadata_v3( zod's discriminated union read one: an array is read as `read_array_metadata_v3` reads it, a group as `read_group_metadata_v3` does, and a document that says neither, or is not an object, is - `ZarrV3UnknownNodeReading`, with the problem. So no caller reads - `node_type` from JSON it has not read. + `ZarrV3UnknownNodeReading`, with the problems, its `zarr_format`'s + among them. So no caller reads `node_type` from JSON it has not read, + and a document of another format says it is not v3. """ node_type, problems = _node_type(value) if node_type == "array": @@ -465,16 +513,26 @@ def _read_node_v3( def _node_type(value: object) -> tuple[str | None, tuple[ValidationProblem, ...]]: - """The node type `value` says it is, one of `_NODE_TYPES`; None, with the problem, when it says none of them, or is not an object.""" + """The node type `value` says it is, one of `_NODE_TYPES`; None, with the problems, when it says none of them, or is not an object. + + A document that says none is judged by its `zarr_format` too, so one + of another format says it is not v3. + """ if not isinstance(value, Mapping): return None, not_an_object(value) document = cast("Mapping[object, object]", value) - if "node_type" not in document: - return None, (ValidationProblem(("node_type",), "missing required key", "missing_key"),) - node_type = document["node_type"] + node_type = document.get("node_type") if isinstance(node_type, str) and node_type in _NODE_TYPES: return node_type, () - return None, with_input((outside_of(("node_type",), node_type, _NODE_TYPES),), document) + problems = [ + *missing_keys(frozenset({"zarr_format"}), document), + *check_literal(document, "zarr_format", 3), + ] + if "node_type" not in document: + problems.append(ValidationProblem(("node_type",), "missing required key", "missing_key")) + else: + problems.append(outside_of(("node_type",), node_type, _NODE_TYPES)) + return None, with_input(problems, document) @dataclass(frozen=True, slots=True) @@ -544,6 +602,8 @@ def read_group_v3( return reading, GroupMembersV3(attributes, extra_fields, held) +T = TypeVar("T") + _CONSOLIDATED_MEMBERS: Final = ("kind", "must_understand", "metadata") """The members of an inline `consolidated_metadata`, in the order the convention declares them.""" @@ -570,6 +630,7 @@ def _read_consolidated_v3( problems.extend(check_literal(env, "must_understand", False)) readings: dict[str, ZarrV3NodeMetadataReading] = {} members: dict[str, ArrayMembersV3 | GroupMembersV3] = {} + node_types: dict[str, NodeType | None] = {} entries = env.get("metadata") if "metadata" in env and not isinstance(entries, Mapping): problems.append(ValidationProblem(("metadata",), "expected an object", "invalid_type")) @@ -580,13 +641,157 @@ def _read_consolidated_v3( ValidationProblem(("metadata",), f"non-string key {key!r}", "invalid_type") ) continue + faults = _key_problems(key) + problems.extend(faults) readings[key], child = _read_node_v3(entry, context) if child is not None: members[key] = child problems.extend(_prefix("metadata", _prefix(key, readings[key].problems))) + if len(faults) == 0: + node_types[key] = _node_type_of(readings[key]) + problems.extend(_hierarchy_problems(node_types)) + for key in node_types: + problems.extend( + _nested_listing_problems( + key, _reading_listing(readings[key]), node_types, _node_type_of + ) + ) return readings, members, tuple(problems) +def group_key(model: ZarrV3GroupMetadata) -> tuple[object, ...]: + """What `==` and `hash` compare of a v3 group model: its attributes and extra fields as JSON text, and what its consolidated metadata holds, by `consolidated_key`.""" + consolidated = model.consolidated_metadata + return ( + json_text(model.attributes), + UNSET if consolidated is UNSET else consolidated_key(consolidated), + json_text(model.extra_fields), + ) + + +def consolidated_key(model: ZarrV3ConsolidatedMetadata) -> tuple[object, ...]: + """What `==` and `hash` compare of consolidated metadata: each document's key, by its path, in path order.""" + return tuple( + (path, array_key(node) if isinstance(node, ZarrV3ArrayMetadata) else group_key(node)) + for path, node in sorted(model.metadata.items(), key=lambda item: item[0]) + ) + + +def _key_problems(key: str) -> list[ValidationProblem]: + """What keeps `key` from being where consolidated metadata keeps a document, said in one problem at the key. + + Consolidated metadata holds the hierarchy below its group, the group its + root, and the reference implementation keeps the document of each node + at the node's path in that hierarchy without its leading `/`: the node + at `/a/b` at the key `a/b`. + """ + faults = _below_faults(key) + if len(faults) == 0: + return [] + message = f"expected the path of a node below the group, got {shown(key)}, which {said(faults)}" + return [ValidationProblem(("metadata", key), message, "invalid_value")] + + +def _nested_listing_problems( + key: str, + listing: Mapping[str, T], + node_types: Mapping[str, NodeType | None], + node_type: Callable[[T], NodeType | None], +) -> list[ValidationProblem]: + """What is wrong with `listing`, the own consolidated listing of the group at `key`, against `node_types`, the group's flat listing: each problem at the nested entry. + + The reference implementation lists every node below the group in the + group's own listing, flat, and gives each group it lists an empty + listing of its own. So a node a listed group lists is one the group + lists too, at the joined key, of the same node type: one it lists + alone would be dropped by the reference reader, and one it lists as + another type contradicts the tree. Only the listing's own entries are + judged: what a group listed there lists in turn is that group's own to + judge, when its document is read. `node_type` says what each entry is, + so readings and models are judged alike. + """ + problems: list[ValidationProblem] = [] + for path, entry in listing.items(): + if len(_below_faults(path)) != 0: + # Its own reader reports a key that is no node's path. + continue + joined = f"{key}/{path}" + here = ("metadata", key, ZARR_V3_CONSOLIDATED_METADATA_KEY, "metadata", path) + if joined not in node_types: + message = ( + f"expected a node the group lists, got {shown(f'/{joined}')}, which " + f"{shown(f'/{key}')} lists alone" + ) + problems.append(ValidationProblem(here, message, "invalid_value")) + continue + listed, nested = node_types[joined], node_type(entry) + if listed is not None and nested is not None and listed != nested: + message = ( + f"expected {_an(listed)}, as the group lists {shown(f'/{joined}')}, " + f"got {_an(nested)}" + ) + problems.append(ValidationProblem(here, message, "invalid_value")) + return problems + + +def _an(node_type: NodeType) -> str: + return "an array" if node_type == "array" else "a group" + + +def _model_node_type(node: ZarrV3ArrayMetadata | ZarrV3GroupMetadata) -> NodeType: + """The node type a model is.""" + return "array" if isinstance(node, ZarrV3ArrayMetadata) else "group" + + +def _model_listing( + node: ZarrV3ArrayMetadata | ZarrV3GroupMetadata, +) -> Mapping[str, ZarrV3ArrayMetadata | ZarrV3GroupMetadata]: + """What a model lists in its own consolidated metadata: nothing, for an array or a group with none.""" + if isinstance(node, ZarrV3GroupMetadata) and node.consolidated_metadata is not UNSET: + return node.consolidated_metadata.metadata + return {} + + +def _reading_listing(reading: ZarrV3NodeMetadataReading) -> Mapping[str, ZarrV3NodeMetadataReading]: + """What a reading lists in its own consolidated metadata: nothing, for an array's or one of no node type.""" + if isinstance(reading, ZarrV3GroupMetadataReading): + return reading.consolidated + return {} + + +def _hierarchy_problems(node_types: Mapping[str, NodeType | None]) -> list[ValidationProblem]: + """What keeps the documents consolidated metadata keeps and its group from making a hierarchy, the group its root, as `hierarchy_problems` judges one: each at the key it is about. + + `node_types` gives the node type of each document by its key, None for + a document of no node type the spec defines, and holds only keys + `_key_problems` finds nothing wrong with. + """ + nodes: dict[str, NodeType | None] = {"/": "group"} + nodes.update((f"/{key}", node_type) for key, node_type in node_types.items()) + return [ + ValidationProblem(("metadata", cast("str", found.loc[0])[1:]), found.message, found.kind) + for found in hierarchy_problems(nodes) + ] + + +def _node_type_of(reading: ZarrV3NodeMetadataReading) -> NodeType | None: + """The node type a document says it is, as its reading tells; None when it says none.""" + if isinstance(reading, ZarrV3ArrayMetadataReading): + return "array" + if isinstance(reading, ZarrV3GroupMetadataReading): + return "group" + return None + + +def _below_faults(path: str) -> list[str]: + """What keeps `path` from being the path of a node below a group, relative to the group, each said.""" + if path == "": + return ["is the group's own"] + if path.startswith("/"): + return ['starts with "/"'] + return path_faults(f"/{path}") + + def _with_models( reading: ZarrV3GroupMetadataReading, members: GroupMembersV3 ) -> ZarrV3GroupMetadataReading: @@ -734,6 +939,15 @@ def update(self, **kwargs: Unpack[ZarrV2GroupMetadataPartial]) -> ZarrV2GroupMet """ return dataclasses.replace(self, **kwargs) + def __eq__(self, other: object) -> bool: + """Whether `other` models the same group: the same document, as JSON text, which takes `NaN` for itself; equal models hash alike.""" + if type(other) is not type(self): + return NotImplemented + return json_text(self.to_json()) == json_text(cast("ZarrV2GroupMetadata", other).to_json()) + + def __hash__(self) -> int: + return hash(json_text(self.to_json())) + def to_json(self) -> ZarrV2GroupMetadataJSON: """Return the merged in-memory document form. @@ -772,8 +986,9 @@ def from_key_value(cls, mapping: Mapping[StoreKey, bytes]) -> ZarrV2GroupMetadat return cls.from_json(zgroup_raw) zgroup = cast("Mapping[str, object]", zgroup_raw) if "attributes" in zgroup: + # A key `.zgroup` does not declare: its attributes are `.zattrs`. refused = ValidationProblem( - ("attributes",), "unexpected document member", "invalid_value" + ("attributes",), "unexpected key 'attributes'", "unknown_key" ) raise MetadataValidationError(with_input((refused,), zgroup)) if ZARR_V2_ATTRIBUTES_STORE_KEY in mapping: @@ -828,6 +1043,17 @@ def __post_init__(self) -> None: raise MetadataValidationError(problems) object.__setattr__(self, "metadata", refined) + def __eq__(self, other: object) -> bool: + """Whether `other` holds the same document: the same JSON text; equal ones hash alike.""" + if type(other) is not type(self): + return NotImplemented + return json_text(self.to_json()) == json_text( + cast("ZarrV2ConsolidatedMetadata", other).to_json() + ) + + def __hash__(self) -> int: + return hash(json_text(self.to_json())) + def to_json(self) -> dict[str, JSONValue]: """The `.zmetadata` document as JSON, sharing no mutable state with the model.""" # to_json output shares no mutable state with the model. @@ -889,13 +1115,7 @@ def _read_consolidated_v2( for key in ("zarr_consolidated_format", "metadata") if key not in doc ] - problems.extend( - ValidationProblem((key,), "unexpected document member", "invalid_value") - if isinstance(key, str) - else ValidationProblem((), f"non-string document key {key!r}", "invalid_type") - for key in doc - if key not in {"zarr_consolidated_format", "metadata"} - ) + problems.extend(unexpected_keys(frozenset({"zarr_consolidated_format", "metadata"}), doc)) problems.extend(check_literal(doc, "zarr_consolidated_format", 1)) refined: dict[str, JSONValue] = {} if "metadata" in doc: diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_json_schema.py b/packages/zarr-metadata/src/zarr_metadata/model/_json_schema.py index 3b6b015fd2..227a5a1916 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_json_schema.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_json_schema.py @@ -36,8 +36,9 @@ def node_metadata_json_schema_v3(*, context: Context = CORE_AND_EXTENSIONS) -> J A JSON Schema says what each member is, and what the rules say of members read together is not in it: one dimension name per dimension of the shape, a chunk grid that fits the shape, codecs in the order a - pipeline takes them, each against the chunk it is handed, and what a - definition's `rules` say. So a document it accepts may still have a + pipeline takes them, each against the chunk it is handed, the + hierarchy the documents of consolidated metadata make below their + group, and what a definition's `rules` say. So a document it accepts may still have a problem, and a JSON document `validate_node_metadata_v3` finds none with, it accepts. A validator reads JSON as a parser gives it, arrays as lists: a model's `to_json` writes tuples, which a Python validator diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_validation.py b/packages/zarr-metadata/src/zarr_metadata/model/_validation.py index f08312ced3..090de80b0d 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_validation.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_validation.py @@ -135,7 +135,7 @@ def missing_keys( def unexpected_keys( allowed: frozenset[str], doc: Mapping[object, object] ) -> tuple[ValidationProblem, ...]: - """One problem per member outside a closed document's declared shape.""" + """One problem per member outside a closed document's declared shape: `unknown_key`, as a closed TypedDict's checker reports one, so a caller who tolerates a member another writer added can tell it from a wrong value.""" problems: list[ValidationProblem] = [] for key in doc: if not isinstance(key, str): @@ -143,9 +143,7 @@ def unexpected_keys( ValidationProblem((), f"non-string document key {key!r}", "invalid_type") ) elif key not in allowed: - problems.append( - ValidationProblem((key,), "unexpected document member", "invalid_value") - ) + problems.append(ValidationProblem((key,), f"unexpected key {key!r}", "unknown_key")) return tuple(problems) diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/__init__.py b/packages/zarr-metadata/src/zarr_metadata/v3/__init__.py index 4e335f9573..9879db759f 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/__init__.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/__init__.py @@ -1,11 +1,14 @@ """Zarr v3 metadata types.""" from zarr_metadata.v3._common import ZarrV3MetadataFieldJSON +from zarr_metadata.v3._hierarchy import NodeName, NodePath from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON, ZarrV3ExtensionField from zarr_metadata.v3.consolidated import ZarrV3ConsolidatedMetadataJSON from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON __all__ = [ + "NodeName", + "NodePath", "ZarrV3ArrayMetadataJSON", "ZarrV3ConsolidatedMetadataJSON", "ZarrV3ExtensionField", diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_common.py b/packages/zarr-metadata/src/zarr_metadata/v3/_common.py index 1347130a6b..3ccc21e1e8 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_common.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_common.py @@ -68,6 +68,10 @@ def validate_metadata_field_v3( return with_input((*envelope, *_configuration_json_problems(value)), value) +ENVELOPE_KEYS: frozenset[str] = frozenset({"name", "configuration", "must_understand"}) +"""The members a metadata field's envelope declares: a key beside them is an unknown key.""" + + def envelope_problems( value: object, *, allow_must_understand_false: bool ) -> tuple[ValidationProblem, ...]: @@ -90,16 +94,13 @@ def envelope_problems( ) field = cast("Mapping[object, object]", value) problems: list[ValidationProblem] = [] - allowed_keys = frozenset({"name", "configuration", "must_understand"}) for key in field: if not isinstance(key, str): problems.append( ValidationProblem((), f"non-string metadata field key {key!r}", "invalid_type") ) - elif key not in allowed_keys: - problems.append( - ValidationProblem((key,), "unexpected metadata field member", "invalid_value") - ) + elif key not in ENVELOPE_KEYS: + problems.append(ValidationProblem((key,), f"unexpected key {key!r}", "unknown_key")) if not isinstance(field.get("name"), str): problems.append(ValidationProblem(("name",), "expected a string name", "invalid_type")) if "configuration" in field: @@ -165,6 +166,7 @@ def parse_metadata_field_v3(value: object) -> ZarrV3MetadataFieldJSON: __all__ = [ + "ENVELOPE_KEYS", "ChunkGridField", "ChunkKeyEncodingField", "CodecField", diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py index 0c589b9db5..4e2c154d73 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py @@ -51,7 +51,14 @@ from typing_extensions import TypeAliasType, TypedDict, TypeVar, is_typeddict from zarr_metadata._common import JSONValue, ZarrV3NamedConfigJSON -from zarr_metadata._json import ValidationProblem, copied, refine_json, shown, with_input +from zarr_metadata._json import ( + ValidationProblem, + copied, + json_text, + refine_json, + shown, + with_input, +) from zarr_metadata._sentinel import UNSET from zarr_metadata._typed_json import ( JSONSchema, @@ -66,6 +73,7 @@ unread_in, ) from zarr_metadata.v3._common import ( + ENVELOPE_KEYS, ChunkGridField, ChunkKeyEncodingField, CodecField, @@ -105,6 +113,11 @@ def unchanged(configuration: T) -> T: return configuration +def fill_value_as_written(configuration: object, nested: object, value: T) -> T: + """The canonical spelling of a fill value of a data type that spells each of its values one way: the fill value as written.""" + return value + + def unknown_lengths(configuration: object, nested: object, shape: tuple[int, ...]) -> Lengths: """The chunk lengths of a grid that says nothing of them: unknown, along each axis of the array.""" return (None,) * len(shape) @@ -333,6 +346,14 @@ class DataTypeDefinition(Definition[C]): scope read them (a struct's field types), and the typed fill value. A data type that says nothing of its fill value takes any JSON. + `fill_value_canonical` spells a fill value that has no problem -- + well typed, and allowed by the rules -- in the one spelling its value + has, so two fill values are one value of the type exactly when their + canonical spellings are written alike: `"NaN"` and `"0x7fc00000"` are + one `float32`, and `0.0` and `-0.0` two. It is handed what the rules + are handed. A data type that says nothing of it spells each of its + values one way: as written. + `storage` says how its values are stored -- in single bytes, in several bytes at a time, or each in as many as it needs -- which is what the `bytes` codec asks of the data type it is handed: an @@ -349,6 +370,8 @@ class DataTypeDefinition(Definition[C]): """The JSON shape of a fill value, as an annotation: `Int8FillValue`.""" 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.""" + fill_value_canonical: Callable[[C, Nested, Any], JSONValue] = fill_value_as_written + """A fill value that has no problem, in the one spelling its value has.""" storage: Callable[[C, Nested], StorageClass | None] = unknown_storage """How its values are stored, given the configuration and the fields it holds; None when unknown.""" @@ -799,6 +822,14 @@ def _as_written(field: _NestedField) -> JSONValue: return field.json +def _declared(field: _NestedField) -> JSONValue: + """A nested field put back as it was written, but for the members its envelope does not declare, which are reported and left out, as the checker leaves out a key a closed TypedDict does not declare.""" + if not isinstance(field.json, Mapping): + return field.json + envelope = cast("Mapping[str, JSONValue]", field.json) + return {key: value for key, value in envelope.items() if key in ENVELOPE_KEYS} + + def _put_back(value: object, put: Callable[[_NestedField], JSONValue]) -> object: """`value` with each nested field the checker handed back put back as `put` gives it.""" if isinstance(value, _NestedField): @@ -864,15 +895,20 @@ def _configuration_checked( The step a definition's `judge` starts from. A member typed with a field alias holds a metadata field, whose envelope is judged as a - document's is: a stray member, or a `must_understand` of `false`, is a - problem of the configuration, and the value does not come back. + document's is: a `must_understand` of `false` is a problem of the + configuration, and the value does not come back; a stray member is an + unknown key, reported and left out, and the value still comes back, + as the checker reports and leaves out a key a closed TypedDict does + not declare. """ refined, problems = refine_json(value, loc) if len(problems) != 0: return None, problems - typed, found, nested = _checked(shape, refined, loc) + typed, found, nested = _typed(shape, refined, loc) problems = (*found, *(problem for field in nested for problem in _envelope(field))) - return (cast("T", typed) if _usable(problems) else None), problems + if not _usable(problems): + return None, problems + return cast("T", _put_back(typed, _declared)), problems def named_configuration( @@ -919,12 +955,14 @@ class Read(Generic[D]): `must_understand` of `false` -- is reported with the field and leaves it read; so is a problem of a field its configuration holds, which is that field's own, as `nested` says. Two fields are equal when they - read the same, however each was spelled: `"bytes"` and - `{"name": "bytes"}` are one field. + read the same, however each was spelled, as `field_key` compares + them: `"bytes"` and `{"name": "bytes"}` are one field, and so are a + blosc with and without the `typesize` that `noshuffle` ignores, which + the definition's `canonical` folds. Equal fields hash alike. """ - json: JSONValue = dataclasses.field(compare=False) - """The field as written, refined: arrays as tuples.""" + json: JSONValue + """The field as written, refined: arrays as tuples; it takes no part in equality.""" name: str """The name it is written with: `"r16"`, though its definition is filed under `r*`.""" definition: D @@ -944,9 +982,17 @@ class Read(Generic[D]): codecs at `("codecs", 0)`: what a definition's functions consult about the fields inside its own. """ - read_as: type[Definition[Any]] = dataclasses.field(init=False, repr=False, compare=False) + read_as: type[Definition[Any]] = dataclasses.field(init=False, repr=False) """The kind of metadata it was read as: its definition's.""" + def __eq__(self, other: object) -> bool: + if not isinstance(other, _FIELDS): + return NotImplemented + return field_key(self) == field_key(cast("Resolved[Any]", other)) + + def __hash__(self) -> int: + return hash(field_key(self)) + def __post_init__(self) -> None: # The runtime half of the annotations: a field read by hand, as an # extension's may be, fails here rather than where a function trusts it. @@ -981,11 +1027,12 @@ class Unclaimed: """A field nothing in scope claims: an extension the scope leaves unjudged, which is what keeps the format open. Equal to another when it is written with the same name and - configuration, however each was spelled. + configuration, however each was spelled: nothing in scope interprets + its configuration, so it compares as JSON text, as `field_key` says. """ - json: JSONValue = dataclasses.field(compare=False) - """The field as written, refined: arrays as tuples.""" + json: JSONValue + """The field as written, refined: arrays as tuples; it takes no part in equality.""" name: str """The name nothing in scope claims.""" read_as: type[Definition[Any]] @@ -993,6 +1040,14 @@ class Unclaimed: configuration: Mapping[str, JSONValue] = dataclasses.field(init=False) """The configuration as written, which nothing judged; empty when none is written.""" + def __eq__(self, other: object) -> bool: + if not isinstance(other, _FIELDS): + return NotImplemented + return field_key(self) == field_key(cast("Resolved[Any]", other)) + + def __hash__(self) -> int: + return hash(field_key(self)) + def __post_init__(self) -> None: # The runtime half of the annotations; `read_as` with its type # arguments dropped, as `resolve` drops them. @@ -1035,6 +1090,14 @@ class Refused(Generic[D]): nested: Nested = dataclasses.field(default_factory=_nothing_nested) """The fields its configuration holds, each as the scope read it; empty when its configuration was not checked against its TypedDict.""" + def __eq__(self, other: object) -> bool: + if not isinstance(other, _FIELDS): + return NotImplemented + return field_key(self) == field_key(cast("Resolved[Any]", other)) + + def __hash__(self) -> int: + return hash(field_key(self)) + def __post_init__(self) -> None: # The runtime half of the annotations; `read_as` with its type # arguments dropped, as `resolve` drops them. @@ -1063,6 +1126,50 @@ def _misread(definition: object, kind: type[Definition[Any]], name: object) -> s return None +def field_key(field: Resolved[Any]) -> tuple[object, ...]: + """What `==` and `hash` compare of a field: what it means, not how it was spelled. + + A field read compares by the definition that read it, its + configuration in the canonical spelling the definition gives it -- what + `canonical_of` spells -- as JSON text, and the fields it holds, each by + its own key. A field nothing claims compares by its name and its + configuration as written, as JSON text: nothing interprets it. A field + refused compares by what was written, and by what refused it. So two + fields are one when what a reader understands of them reads the same, + and what none interprets is written alike. + """ + if isinstance(field, Read): + definition = cast("Definition[Any]", field.definition) + configuration: JSONValue = dict(field.configuration) + # A field it holds is compared by its own key, so its place holds + # nothing before the definition's `canonical` sees the rest, as + # `_canonical_field` orders it: `canonical` folds only the + # definition's own members. + for loc in field.nested: + configuration = _replaced(configuration, loc, None) + spelled = asked( + definition, + "canonical", + lambda: json_text(cast("JSONValue", definition.canonical(configuration))), + ) + return ("read", definition, spelled, _nested_key(field.nested)) + if isinstance(field, Unclaimed): + return ("unclaimed", field.read_as, field.name, json_text(field.configuration)) + return ( + "refused", + field.read_as, + field.name, + field.definition, + json_text(field.json), + _nested_key(field.nested), + ) + + +def _nested_key(nested: Nested) -> tuple[tuple[Loc, tuple[object, ...]], ...]: + """The fields a configuration holds, each by its key, where it sits.""" + return tuple((loc, field_key(inner)) for loc, inner in nested.items()) + + def document_json(field: Resolved[Any]) -> JSONValue: """A field as a document writes it, holding the field's own values: as `to_json` writes it, or as it was written when it was refused. @@ -1232,6 +1339,55 @@ def fill_value_problems( return with_input((*problems, *refused), value, loc) +def canonical_fill_value( + data_type: Resolved[DataTypeDefinition[Any]], value: object +) -> JSONValue | UNSET: + """`value`, a fill value of `data_type`, a data type field a scope read, in the one spelling its value has; `UNSET` when it has a problem. + + As the data type's `fill_value_canonical` spells it, so two fill + values of a data type are one value exactly when their canonical + spellings are written alike -- the same JSON, as `json.dumps` writes + it, which `==` is not: it takes `-0.0` for `0.0`. A fill value + `fill_value_problems` finds a problem with has no canonical spelling, + as `canonical_of` gives a field with a problem none: `UNSET`, since + `None` is the JSON `null`, a fill value of a data type the scope did + not read, which spells a fill value as written. + """ + if len(fill_value_problems(data_type, value)) != 0: + return UNSET + refined, _ = refine_json(value, ()) + return spelled_canonically(data_type, refined) + + +def spelled_canonically( + data_type: Resolved[DataTypeDefinition[Any]], value: JSONValue +) -> JSONValue: + """`value`, a fill value of `data_type` with no problem, in its canonical spelling, as `canonical_fill_value` gives it, without judging it again. + + Its `fill_value_canonical` is the extension author's code: what it + gives is checked to be JSON, and an error it raises says which data + type's canonical spelling raised it. + """ + if not isinstance(data_type, Read): + return value + definition, configuration = data_type.definition, data_type.configuration + spelled = asked( + definition, + "fill_value_canonical", + lambda: cast( + "object", definition.fill_value_canonical(configuration, data_type.nested, value) + ), + ) + refined, problems = refine_json(spelled, ()) + if len(problems) != 0: + msg = ( + f"{definition.name!r}: its fill_value_canonical gives JSON, got {spelled!r}: " + f"{problems[0].message}" + ) + raise TypeError(msg) + return refined + + def storage_of(data_type: Resolved[DataTypeDefinition[Any]]) -> StorageClass | None: """How the values of `data_type`, a data type field a scope read, are stored; None when unknown. @@ -1588,13 +1744,16 @@ def _replaced(value: JSONValue, path: Loc, new: JSONValue) -> JSONValue: "Unclaimed", "as_kind", "asked", + "canonical_fill_value", "canonical_of", "canonicalize", "chunk_grid_lengths", "configuration_of", "field_json_schema", + "field_key", "field_kind", "field_schemas", + "fill_value_as_written", "fill_value_problems", "kind_of", "multi_byte", @@ -1605,6 +1764,7 @@ def _replaced(value: JSONValue, path: Loc, new: JSONValue) -> JSONValue: "ruled", "single_byte", "spelled", + "spelled_canonically", "storage_of", "unchanged", "unknown_chunk", diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_hierarchy.py b/packages/zarr-metadata/src/zarr_metadata/v3/_hierarchy.py new file mode 100644 index 0000000000..7b6cac919c --- /dev/null +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_hierarchy.py @@ -0,0 +1,287 @@ +"""A Zarr v3 hierarchy: the names and paths of its nodes, and the tree they make. + +`NodeName` and `NodePath` are modelled on zarrs' types of those names, and +hold the spec's rules, which reserve `zarr.json` too. `hierarchy_problems` +judges the node type of each node of a hierarchy, by its path, as a tree. + +Every problem here is one per value, and says its reasons at once, so +what is reported stays proportional to what was read: a path of a +thousand bad names is one problem, not a thousand each repeating the +path. + +Private: consumers import `NodeName` and `NodePath` from `zarr_metadata.v3`, +and the validators from `zarr_metadata.model`. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal, NewType, TypeGuard, cast + +from zarr_metadata._json import MetadataValidationError, ValidationProblem, shown, with_input + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + +NodeName = NewType("NodeName", str) +"""The name of a node in a Zarr v3 hierarchy. + +The root's is `""`. Any other is not empty, holds no `/`, is not periods +alone -- `.`, `..` -- does not start with the reserved `__`, and is not +`zarr.json`. Case matters: `foo` and `FOO` are two names +(https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/core/index.rst#L818-L837). +""" + +NodePath = NewType("NodePath", str) +"""The path of a node in a Zarr v3 hierarchy. + +The root's is `/`. Any other's is its parent's path, a `/` unless the +parent is the root, and its name: so a path starts with `/`, does not end +with one, and holds a node name between each two +(https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/core/index.rst#L211-L229). +""" + +NodeType = Literal["array", "group"] +"""The two kinds of node a hierarchy holds.""" + + +def said(faults: Sequence[str]) -> str: + """`faults`, each a reason, as one clause: `a`, `a and b`, `a, b and c`.""" + if len(faults) <= 1: + return "".join(faults) + return f"{', '.join(faults[:-1])} and {faults[-1]}" + + +def name_faults(name: str) -> list[str]: + """What keeps `name` from being a node name, each said; none for a node name, the root's `""` among them.""" + faults: list[str] = [] + if "/" in name: + faults.append('holds "/"') + if name != "" and set(name) == {"."}: + faults.append("is periods alone") + if name.startswith("__"): + faults.append('starts with the reserved "__"') + if name == "zarr.json": + faults.append('is the reserved "zarr.json"') + return faults + + +def names_faults(names: list[str]) -> list[str]: + """What keeps `names`, the names a path holds between its `/`, from being node names below the root: the first that is not one, said, and how many more there are.""" + faulty = [name for name in names if name == "" or len(name_faults(name)) != 0] + if len(faulty) == 0: + return [] + first = faulty[0] + faults = ( + ['holds an empty name between two "/"'] + if first == "" + else [f"holds {shown(first)}, a name that {said(name_faults(first))}"] + ) + if len(faulty) > 1: + more = len(faulty) - 1 + faults.append( + f"holds {more} more name{'s' if more != 1 else ''} that {'are' if more != 1 else 'is'} not a node name" + ) + return faults + + +def path_faults(path: str) -> list[str]: + """What keeps `path` from being a node path, each said; none for a node path, the root's `/` among them.""" + if path == "/": + return [] + if not path.startswith("/"): + return ['does not start with "/"'] + faults: list[str] = [] + names = path[1:].split("/") + if path.endswith("/"): + faults.append('ends with "/"') + names = names[:-1] + return [*faults, *names_faults(names)] + + +def hierarchy_problems(nodes: Mapping[str, NodeType | None]) -> tuple[ValidationProblem, ...]: + """What keeps `nodes`, the node type of each node by its path, from being a Zarr v3 hierarchy: one problem per node it is about, at that node's path. + + "A Zarr hierarchy is a tree structure, where each node in the tree is + either a group or an array. Group nodes may have children but array + nodes may not" + (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/core/index.rst#L177-L181). + So each path is a node path, and each node but the root has its parent + among them, a group: a node below an array is an `invalid_value` at its + path, and the nearest group missing above a node is a `missing_key` at + that group's path, once, saying how many more are missing above it, the + root's among them. A node of no type known, None, is taken as a group: + what makes its type unknown is its own problem, reported where it sits. + A mapping holds each path once, so no two siblings share a name. + """ + problems: list[ValidationProblem] = [] + well_formed: list[str] = [] + for path in nodes: + faults = path_faults(path) + if len(faults) == 0: + well_formed.append(path) + else: + message = f"expected a node path, got {shown(path)}, which {said(faults)}" + problems.append(ValidationProblem((path,), message, "invalid_value")) + tree = _Tree() + for path in well_formed: + tree.hold(path, nodes[path]) + reported: set[str] = set() + for path in well_formed: + if path == "/": + continue + holder, missing = tree.above(path) + if holder == "array": + # No node is below an array, however many groups are missing + # between them. + message = ( + f"expected a node below a group, got {shown(path)}, below the array " + f"{shown(tree.holder_of(path))}" + ) + problems.append(ValidationProblem((path,), message, "invalid_value")) + elif missing != 0: + nearest = path.rpartition("/")[0] or "/" + if nearest not in reported: + reported.add(nearest) + above = missing - 1 + more = ( + "" if above == 0 else f", and {above} group{'s' if above != 1 else ''} above it" + ) + message = f"missing the group holding {shown(path)}{more}" + problems.append(ValidationProblem((nearest,), message, "missing_key")) + return tuple(problems) + + +class _Branch: + """A name in the tree of held paths: whether a node is held there, its type, and the names below it.""" + + __slots__ = ("children", "held", "node_type") + + def __init__(self) -> None: + self.held = False + self.node_type: NodeType | None = None + self.children: dict[str, _Branch] = {} + + +class _Tree: + """The held paths as a tree of their names, so each path is walked once, in time proportional to its length. + + Walking up a path by its ancestors' strings costs the path's length + for each ancestor, which a hostile key of a million characters makes + a quadratic wait; here a path is split once and walked name by name. + """ + + __slots__ = ("root",) + + def __init__(self) -> None: + self.root = _Branch() + + def hold(self, path: str, node_type: NodeType | None) -> None: + """Mark the node at `path`, a node path, as held, of `node_type`.""" + branch = self.root + for name in _names(path): + branch = branch.children.setdefault(name, _Branch()) + branch.held = True + branch.node_type = node_type + + def above(self, path: str) -> tuple[NodeType | None, int]: + """Of the node at `path`, a node path below the root: the type of the nearest held node above it, `"group"` for one of no type known and None when none is held, and how many groups are missing between them.""" + names = _names(path) + branch: _Branch | None = self.root + holder: NodeType | None = None + held_depth = -1 + for depth, name in enumerate(names[:-1], start=0): + if branch is not None and branch.held: + holder, held_depth = branch.node_type or "group", depth + branch = None if branch is None else branch.children.get(name) + # The parent, at the last depth walked, may be held too. + if branch is not None and branch.held: + holder, held_depth = branch.node_type or "group", len(names) - 1 + return holder, len(names) - 1 - held_depth + + def holder_of(self, path: str) -> str: + """The path of the nearest held node above the node at `path`, a node path below the root that has one.""" + names = _names(path) + branch: _Branch | None = self.root + holder = "/" + for depth, name in enumerate(names[:-1]): + if branch is not None and branch.held: + holder = "/" + "/".join(names[:depth]) if depth != 0 else "/" + branch = None if branch is None else branch.children.get(name) + if branch is not None and branch.held: + holder = "/" + "/".join(names[:-1]) + return holder + + +def _names(path: str) -> list[str]: + """The names a node path holds between its `/`: none for the root's.""" + return [] if path == "/" else path[1:].split("/") + + +def _string_problems(value: object, what: str) -> tuple[ValidationProblem, ...]: + return (ValidationProblem((), f"expected {what}, got {shown(value)}", "invalid_type"),) + + +def validate_node_name_v3(value: object) -> tuple[ValidationProblem, ...]: + """Every reason `value` is not a v3 node name, said in one `invalid_value`, or an `invalid_type` for what is not a string.""" + if not isinstance(value, str): + return with_input(_string_problems(value, "a node name"), value) + faults = name_faults(value) + if len(faults) == 0: + return () + message = f"expected a node name, got {shown(value)}, which {said(faults)}" + return with_input((ValidationProblem((), message, "invalid_value"),), value) + + +def is_node_name_v3(value: object) -> TypeGuard[NodeName]: + """Whether `value` is a v3 node name `validate_node_name_v3` finds nothing wrong with.""" + return len(validate_node_name_v3(value)) == 0 + + +def parse_node_name_v3(value: object) -> NodeName: + """`value` as a `NodeName`, or `MetadataValidationError` with every reason it is not one.""" + problems = validate_node_name_v3(value) + if len(problems) != 0: + raise MetadataValidationError(problems) + return NodeName(cast("str", value)) + + +def validate_node_path_v3(value: object) -> tuple[ValidationProblem, ...]: + """Every reason `value` is not a v3 node path, said in one `invalid_value`, or an `invalid_type` for what is not a string.""" + if not isinstance(value, str): + return with_input(_string_problems(value, "a node path"), value) + faults = path_faults(value) + if len(faults) == 0: + return () + message = f"expected a node path, got {shown(value)}, which {said(faults)}" + return with_input((ValidationProblem((), message, "invalid_value"),), value) + + +def is_node_path_v3(value: object) -> TypeGuard[NodePath]: + """Whether `value` is a v3 node path `validate_node_path_v3` finds nothing wrong with.""" + return len(validate_node_path_v3(value)) == 0 + + +def parse_node_path_v3(value: object) -> NodePath: + """`value` as a `NodePath`, or `MetadataValidationError` with every reason it is not one.""" + problems = validate_node_path_v3(value) + if len(problems) != 0: + raise MetadataValidationError(problems) + return NodePath(cast("str", value)) + + +__all__ = [ + "NodeName", + "NodePath", + "NodeType", + "hierarchy_problems", + "is_node_name_v3", + "is_node_path_v3", + "name_faults", + "names_faults", + "parse_node_name_v3", + "parse_node_path_v3", + "path_faults", + "said", + "validate_node_name_v3", + "validate_node_path_v3", +] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/default.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/default.py index c0e49ee543..cc6ab57062 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/default.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/default.py @@ -7,7 +7,7 @@ See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-key-encoding """ -from typing import Final, Literal, NotRequired +from typing import Final, Literal, NotRequired, cast from typing_extensions import TypedDict @@ -54,8 +54,25 @@ class DefaultChunkKeyEncodingObject(TypedDict, closed=True): so the short-hand-name form is permitted in addition to the object form. """ + +def _canonical( + configuration: DefaultChunkKeyEncodingConfiguration, +) -> DefaultChunkKeyEncodingConfiguration: + """Without a `separator` of `/`, which is what an absent one means. + + "If not specified, `separator` defaults to `/`" + (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/chunk-key-encodings/default/index.rst#L27-L29), + so the two spellings are one encoding. + """ + if configuration.get("separator") != "/": + return configuration + return cast("DefaultChunkKeyEncodingConfiguration", {}) + + DEFAULT_CHUNK_KEY_ENCODING: Final = ChunkKeyEncodingDefinition( - name=DEFAULT_CHUNK_KEY_ENCODING_NAME, configuration=DefaultChunkKeyEncodingConfiguration + name=DEFAULT_CHUNK_KEY_ENCODING_NAME, + configuration=DefaultChunkKeyEncodingConfiguration, + canonical=_canonical, ) """The `default` chunk key encoding; its `separator` is typed, so it has no rule of its own.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py index 7c178a599e..4d9bc284c4 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/chunk_key_encoding/v2.py @@ -13,7 +13,7 @@ See https://zarr-specs.readthedocs.io/en/latest/v3/core/index.html#chunk-key-encoding """ -from typing import Final, Literal, NotRequired +from typing import Final, Literal, NotRequired, cast from typing_extensions import TypedDict @@ -60,8 +60,23 @@ class V2ChunkKeyEncodingObject(TypedDict, closed=True): so the short-hand-name form is permitted in addition to the object form. """ + +def _canonical(configuration: V2ChunkKeyEncodingConfiguration) -> V2ChunkKeyEncodingConfiguration: + """Without a `separator` of `.`, which is what an absent one means. + + "If not specified, `separator` defaults to `.`" + (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/chunk-key-encodings/v2/index.rst#L27-L29), + so the two spellings are one encoding. + """ + if configuration.get("separator") != ".": + return configuration + return cast("V2ChunkKeyEncodingConfiguration", {}) + + V2_CHUNK_KEY_ENCODING: Final = ChunkKeyEncodingDefinition( - name=V2_CHUNK_KEY_ENCODING_NAME, configuration=V2ChunkKeyEncodingConfiguration + name=V2_CHUNK_KEY_ENCODING_NAME, + configuration=V2ChunkKeyEncodingConfiguration, + canonical=_canonical, ) """The `v2` chunk key encoding; its `separator` is typed, so it has no rule of its own.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py index 2bf5bd8020..8a56d50a16 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/sharding_indexed.py @@ -5,7 +5,7 @@ """ from collections.abc import Iterator, Mapping -from typing import Annotated, Final, Literal, NotRequired +from typing import Annotated, Final, Literal, NotRequired, cast from annotated_types import Ge from typing_extensions import TypedDict @@ -165,9 +165,27 @@ def _per_shard(chunk_shape: tuple[int, ...], lengths: Lengths | None) -> Lengths ) +def _canonical( + configuration: ShardingIndexedCodecConfiguration, +) -> ShardingIndexedCodecConfiguration: + """Without an `index_location` of `end`, which is what an absent one means. + + "If the parameter is not present, the value defaults to `end`" + (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/codecs/sharding-indexed/index.rst#L157-L161), + so the two spellings are one codec. + """ + if configuration.get("index_location") != "end": + return configuration + return cast( + "ShardingIndexedCodecConfiguration", + {key: value for key, value in configuration.items() if key != "index_location"}, + ) + + SHARDING_INDEXED_CODEC: Final = CodecDefinition( name=SHARDING_INDEXED_CODEC_NAME, configuration=ShardingIndexedCodecConfiguration, + canonical=_canonical, kind="array_bytes", size="dynamic", chunk_rules=_chunk_rules, diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py b/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py index 61a0695b61..55cd471dae 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/codec/zstd.py @@ -6,7 +6,7 @@ proposed the codec, was never merged). """ -from typing import Annotated, Final, Literal, NotRequired +from typing import Annotated, Final, Literal, NotRequired, cast from annotated_types import Interval from typing_extensions import TypedDict @@ -56,9 +56,26 @@ class ZstdCodecObject(TypedDict, closed=True): https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/core/index.rst#L1562-L1564 (short-hand names only "if no configuration metadata is required") """ + +def _canonical(configuration: ZstdCodecConfiguration) -> ZstdCodecConfiguration: + """Without a `checksum` of `false`, which is what an absent one means. + + The spec says of `checksum` that it "should be omitted if false" + (https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/codecs/zstd/README.md?plain=1#L17-L19), + so the two spellings are one codec. + """ + if configuration.get("checksum") is not False: + return configuration + return cast( + "ZstdCodecConfiguration", + {key: value for key, value in configuration.items() if key != "checksum"}, + ) + + ZSTD_CODEC: Final = CodecDefinition( name=ZSTD_CODEC_NAME, configuration=ZstdCodecConfiguration, + canonical=_canonical, kind="bytes_bytes", size="dynamic", ) diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/_float.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/_float.py index 3f7b56b5da..f30b842699 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/_float.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/_float.py @@ -9,10 +9,13 @@ (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/data-types/index.rst#L88-L91). """ +import struct from collections.abc import Callable, Iterable, Iterator from dataclasses import dataclass -from typing import Any, Literal, get_args +from decimal import ROUND_HALF_EVEN, Decimal, localcontext +from typing import Any, Final, Literal, get_args +from zarr_metadata._common import JSONValue from zarr_metadata._json import ValidationProblem, choices, shown from zarr_metadata.v3._definition import EmptyConfiguration, Nested @@ -56,6 +59,116 @@ def __call__( ) +FloatWidth = Literal[16, 32, 64] +"""The widths, in bits, of the IEEE 754 binary formats the float types store.""" + +_FORMATS: Final[dict[FloatWidth, tuple[str, int]]] = {16: ("e", 10), 32: ("f", 23), 64: ("d", 52)} +"""Each width's `struct` format, and how many bits of it hold the fraction.""" + + +def float_fill_value_canonical( + width: FloatWidth, +) -> Callable[[EmptyConfiguration, Nested, float | str], float | str]: + """The canonical spelling of a fill value of the floating-point type `width` bits wide. + + A fill value spells a value of the type, as `float_bits` reads one: a + number, a named value, or the value's bits. Its canonical spelling is + the named value for an infinity, or for the NaN the spec names + `"NaN"`; the hex string of its bits, in lower case, for any other NaN; + and, for any other value, the shortest number that rounds to it, the + nearest of those, as numpy and `repr` spell one -- `0.1` for the + `float32` nearest `0.1` -- `-0.0`, a value of its own, among them. + """ + return _FloatCanonical(width) + + +@dataclass(frozen=True, slots=True) +class _FloatCanonical: + """A float fill value's canonical spelling: a value rather than a closure, as `_FloatFillValue` is.""" + + width: FloatWidth + + def __call__( + self, configuration: EmptyConfiguration, nested: Nested, value: float | str + ) -> float | str: + return _spelled(float_bits(value, self.width), self.width) + + +def float_bits(value: float | str, width: FloatWidth) -> int: + """The bits of the value `value`, a float fill value the rules allow, spells in the type `width` bits wide. + + A number is read as a float64, as a JSON parser reads one -- an integer + of more digits than a float64 holds is rounded to one -- and rounded to + the nearest value the type represents, ties to even, and to an infinity + past the largest, as numpy casts a float64. So an integer and a number + with a fraction that read as one float64 spell one value. + """ + code, fraction = _FORMATS[width] + exponent = width - 1 - fraction + infinity = ((1 << exponent) - 1) << fraction + sign = 1 << (width - 1) + if isinstance(value, str): + named = { + "NaN": infinity | (1 << (fraction - 1)), + "Infinity": infinity, + "-Infinity": sign | infinity, + } + return named[value] if value in named else int(value, 16) + try: + held = float(value) + except OverflowError: + # An integer past the largest float64 reads as an infinity. + return (sign if value < 0 else 0) | infinity + try: + return int.from_bytes(struct.pack(f">{code}", held), "big") + except OverflowError: + # `struct` refuses a float64 that rounds past the type's largest value. + return (sign if held < 0 else 0) | infinity + + +def _spelled(bits: int, width: FloatWidth) -> float | str: + """The canonical spelling of the value whose bits, in the type `width` bits wide, are `bits`.""" + code, fraction = _FORMATS[width] + exponent = width - 1 - fraction + infinity = ((1 << exponent) - 1) << fraction + sign = 1 << (width - 1) + if bits & infinity == infinity: + if bits & ((1 << fraction) - 1) == 0: + return "-Infinity" if bits & sign else "Infinity" + if bits == infinity | (1 << (fraction - 1)): + return "NaN" + return f"0x{bits:0{width // 4}x}" + value: float = struct.unpack(f">{code}", bits.to_bytes(width // 8, "big"))[0] + if width == 64 or value == 0: + # A float64 is its own shortest spelling, as `repr` writes it, and + # so is a zero of either sign. + return value + return _shortest(value, bits, width) + + +def _shortest(value: float, bits: int, width: FloatWidth) -> float: + """The shortest number that rounds to `value`, whose bits in the type `width` bits wide are `bits`: of the fewest significant digits, the nearest to it. + + Of each number of digits the nearest is tried, and then the one past + `value` from it: at a power of two the numbers that round to it reach + twice as far above it as below, so the nearest may miss where the next + one does not. + """ + exact = Decimal(value) + for digits in range(1, 18): + with localcontext() as context: + context.prec = digits + context.rounding = ROUND_HALF_EVEN + nearest = +exact + step = Decimal((0, (1,), nearest.adjusted() - digits + 1)) + beyond = nearest + step if nearest < exact else nearest - step + for candidate in (nearest, beyond): + if float_bits(float(candidate), width) == bits: + return float(candidate) + # Seventeen significant digits tell every float64 from every other. + return value + + def complex_fill_value_rules( component: Callable[[EmptyConfiguration, Nested, Any], Iterable[ValidationProblem]], ) -> Callable[ @@ -85,4 +198,34 @@ def __call__( yield ValidationProblem((index, *found.loc), found.message, found.kind) -__all__ = ["FloatSpecialFillValue", "complex_fill_value_rules", "float_fill_value_rules"] +def complex_fill_value_canonical( + component: Callable[[EmptyConfiguration, Nested, Any], JSONValue], +) -> Callable[[EmptyConfiguration, Nested, tuple[float | str, float | str]], JSONValue]: + """The canonical spelling of a complex fill value: each component in the canonical spelling `component`, its float type's, gives it.""" + return _ComplexCanonical(component) + + +@dataclass(frozen=True, slots=True) +class _ComplexCanonical: + """A complex fill value's canonical spelling: a value rather than a closure, as `_FloatFillValue` is.""" + + component: Callable[[EmptyConfiguration, Nested, Any], JSONValue] + + def __call__( + self, + configuration: EmptyConfiguration, + nested: Nested, + value: tuple[float | str, float | str], + ) -> JSONValue: + return tuple(self.component(configuration, nested, part) for part in value) + + +__all__ = [ + "FloatSpecialFillValue", + "FloatWidth", + "complex_fill_value_canonical", + "complex_fill_value_rules", + "float_bits", + "float_fill_value_canonical", + "float_fill_value_rules", +] 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 ffc0ce2aab..de5c0c7d09 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 @@ -24,6 +24,24 @@ https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/data-types/numpy.datetime64/README.md?plain=1#L109-L112 """ +NOT_A_TIME_TICKS: Final = -(2**63) +"""The tick count `NaT` is stored as, which a fill value may write for it. + +"`"fill_value": "NaT"` and `"fill_value": -9223372036854775808` should +be treated as equivalent representations of the same scalar value" +(https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/data-types/numpy.datetime64/README.md?plain=1#L114-L116); +`numpy.timedelta64` says the same +(https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/data-types/numpy.timedelta64/README.md?plain=1#L117-L119). +""" + + +def numpy_time_fill_value_canonical( + configuration: object, nested: object, value: int | str +) -> int | str: + """The canonical spelling of a numpy time fill value: `"NaT"` for `NaT`, however it is written, and any other count of ticks as written.""" + return "NaT" if value in ("NaT", NOT_A_TIME_TICKS) else value + + numpy_time_storage: Final = multi_byte """Signed 64-bit integers, in the byte order the codecs say. @@ -38,8 +56,10 @@ __all__ = [ + "NOT_A_TIME_TICKS", "NUMPY_TIME_MAX_SCALE_FACTOR", "NumpyTimeScaleFactor", "NumpyTimeTicks", + "numpy_time_fill_value_canonical", "numpy_time_storage", ] diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bytes.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bytes.py index 62a266ffc9..aa83447ef3 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bytes.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/bytes.py @@ -4,6 +4,7 @@ See https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/data-types/bytes/README.md """ +import base64 import re from collections.abc import Iterator from typing import Final, Literal, NewType @@ -63,11 +64,26 @@ def _fill_value_rules( ) +def _fill_value_canonical( + configuration: EmptyConfiguration, nested: Nested, value: BytesFillValue +) -> str: + """The bytes, however written, as the base64 that encodes them. + + The string "is more compact" + (https://github.com/zarr-developers/zarr-extensions/blob/4da7b37a84f76e660902f6d3de3eaef0e0febae6/data-types/bytes/README.md?plain=1#L11), + and encoding the bytes again spells them one way: `"QR=="` decodes to + the one byte `"QQ=="` does. + """ + data = base64.b64decode(value) if isinstance(value, str) else bytes(value) + return base64.b64encode(data).decode("ascii") + + BYTES_DATA_TYPE: Final = DataTypeDefinition( name=BYTES_DATA_TYPE_NAME, configuration=EmptyConfiguration, fill_value=BytesFillValue, fill_value_rules=_fill_value_rules, + fill_value_canonical=_fill_value_canonical, storage=variable_length, ) """The `bytes` data type: a bare name, with nothing to configure. diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex128.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex128.py index 509b12f30a..bf3d55de87 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex128.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex128.py @@ -7,7 +7,10 @@ from typing import Final, Literal from zarr_metadata.v3._definition import DataTypeDefinition, EmptyConfiguration, multi_byte -from zarr_metadata.v3.data_type._float import complex_fill_value_rules +from zarr_metadata.v3.data_type._float import ( + complex_fill_value_canonical, + complex_fill_value_rules, +) from zarr_metadata.v3.data_type.float64 import FLOAT64_DATA_TYPE, Float64FillValue COMPLEX128_DATA_TYPE_NAME: Final = "complex128" @@ -36,6 +39,7 @@ configuration=EmptyConfiguration, fill_value=Complex128FillValue, fill_value_rules=complex_fill_value_rules(FLOAT64_DATA_TYPE.fill_value_rules), + fill_value_canonical=complex_fill_value_canonical(FLOAT64_DATA_TYPE.fill_value_canonical), storage=multi_byte, ) """The `complex128` data type: a bare name, with nothing to configure; its fill value a pair of `float64` components.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex64.py index ceb1576473..5ddd0559f8 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex64.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/complex64.py @@ -7,7 +7,10 @@ from typing import Final, Literal from zarr_metadata.v3._definition import DataTypeDefinition, EmptyConfiguration, multi_byte -from zarr_metadata.v3.data_type._float import complex_fill_value_rules +from zarr_metadata.v3.data_type._float import ( + complex_fill_value_canonical, + complex_fill_value_rules, +) from zarr_metadata.v3.data_type.float32 import FLOAT32_DATA_TYPE, Float32FillValue COMPLEX64_DATA_TYPE_NAME: Final = "complex64" @@ -36,6 +39,7 @@ configuration=EmptyConfiguration, fill_value=Complex64FillValue, fill_value_rules=complex_fill_value_rules(FLOAT32_DATA_TYPE.fill_value_rules), + fill_value_canonical=complex_fill_value_canonical(FLOAT32_DATA_TYPE.fill_value_canonical), storage=multi_byte, ) """The `complex64` data type: a bare name, with nothing to configure; its fill value a pair of `float32` components.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float16.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float16.py index 33ba182dc4..1a53e8bca1 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float16.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float16.py @@ -8,7 +8,11 @@ from typing import Final, Literal, NewType from zarr_metadata.v3._definition import DataTypeDefinition, EmptyConfiguration, multi_byte -from zarr_metadata.v3.data_type._float import FloatSpecialFillValue, float_fill_value_rules +from zarr_metadata.v3.data_type._float import ( + FloatSpecialFillValue, + float_fill_value_canonical, + float_fill_value_rules, +) FLOAT16_DATA_TYPE_NAME: Final = "float16" """The `data_type` value for the `float16` type.""" @@ -69,6 +73,7 @@ def hex_float16(value: str) -> HexFloat16: configuration=EmptyConfiguration, fill_value=Float16FillValue, fill_value_rules=float_fill_value_rules("float16", hex_float16), + fill_value_canonical=float_fill_value_canonical(16), storage=multi_byte, ) """The `float16` data type: a bare name, with nothing to configure; its fill value a number, a named value or a hex string.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float32.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float32.py index 7eb923d581..35e9706ae0 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float32.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float32.py @@ -8,7 +8,11 @@ from typing import Final, Literal, NewType from zarr_metadata.v3._definition import DataTypeDefinition, EmptyConfiguration, multi_byte -from zarr_metadata.v3.data_type._float import FloatSpecialFillValue, float_fill_value_rules +from zarr_metadata.v3.data_type._float import ( + FloatSpecialFillValue, + float_fill_value_canonical, + float_fill_value_rules, +) FLOAT32_DATA_TYPE_NAME: Final = "float32" """The `data_type` value for the `float32` type.""" @@ -69,6 +73,7 @@ def hex_float32(value: str) -> HexFloat32: configuration=EmptyConfiguration, fill_value=Float32FillValue, fill_value_rules=float_fill_value_rules("float32", hex_float32), + fill_value_canonical=float_fill_value_canonical(32), storage=multi_byte, ) """The `float32` data type: a bare name, with nothing to configure; its fill value a number, a named value or a hex string.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float64.py index 0363439cfa..a086ed50a5 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float64.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/float64.py @@ -8,7 +8,11 @@ from typing import Final, Literal, NewType from zarr_metadata.v3._definition import DataTypeDefinition, EmptyConfiguration, multi_byte -from zarr_metadata.v3.data_type._float import FloatSpecialFillValue, float_fill_value_rules +from zarr_metadata.v3.data_type._float import ( + FloatSpecialFillValue, + float_fill_value_canonical, + float_fill_value_rules, +) FLOAT64_DATA_TYPE_NAME: Final = "float64" """The `data_type` value for the `float64` type.""" @@ -70,6 +74,7 @@ def hex_float64(value: str) -> HexFloat64: configuration=EmptyConfiguration, fill_value=Float64FillValue, fill_value_rules=float_fill_value_rules("float64", hex_float64), + fill_value_canonical=float_fill_value_canonical(64), storage=multi_byte, ) """The `float64` data type: a bare name, with nothing to configure; its fill value a number, a named value or a hex string.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py index 365df13446..4464c93d4d 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_datetime64.py @@ -12,6 +12,7 @@ from zarr_metadata.v3.data_type._numpy_time import ( NumpyTimeScaleFactor, NumpyTimeTicks, + numpy_time_fill_value_canonical, numpy_time_storage, ) @@ -62,6 +63,7 @@ class NumpyDatetime64(TypedDict, closed=True): name=NUMPY_DATETIME64_DATA_TYPE_NAME, configuration=NumpyDatetime64Configuration, fill_value=NumpyDatetime64FillValue, + fill_value_canonical=numpy_time_fill_value_canonical, storage=numpy_time_storage, ) """The `numpy.datetime64` data type.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py index 2f11f45526..0aa75d3559 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/numpy_timedelta64.py @@ -12,6 +12,7 @@ from zarr_metadata.v3.data_type._numpy_time import ( NumpyTimeScaleFactor, NumpyTimeTicks, + numpy_time_fill_value_canonical, numpy_time_storage, ) @@ -81,6 +82,7 @@ class NumpyTimedelta64(TypedDict, closed=True): name=NUMPY_TIMEDELTA64_DATA_TYPE_NAME, configuration=NumpyTimedelta64Configuration, fill_value=NumpyTimedelta64FillValue, + fill_value_canonical=numpy_time_fill_value_canonical, storage=numpy_time_storage, ) """The `numpy.timedelta64` data type.""" 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 140f8ae847..0aa0f55257 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 @@ -17,6 +17,7 @@ Nested, StorageClass, fill_value_problems, + spelled_canonically, storage_of, ) @@ -128,6 +129,23 @@ def _fill_value_rules( yield ValidationProblem((key,), f"no struct field is named {key!r}", "unknown_key") +def _fill_value_canonical( + configuration: StructConfiguration, nested: Nested, value: StructFillValue +) -> dict[str, JSONValue]: + """Each field's fill value in the canonical spelling of that field's own type, in the order the fields are declared. + + A field type the scope did not read, or whose reading the struct's does + not hold, spells its fill value as written. + """ + spelled: dict[str, JSONValue] = {} + for index, member in enumerate(configuration["fields"]): + name = member["name"] + field_type = nested.get(("fields", index, "data_type")) + held = value[name] + spelled[name] = held if field_type is None else spelled_canonically(field_type, held) + return spelled + + def _storage(configuration: StructConfiguration, nested: Nested) -> StorageClass | None: """Its fields' values, packed together: numbers of several bytes if any field holds them, single bytes if every field is made of them. @@ -160,6 +178,7 @@ def _storage(configuration: StructConfiguration, nested: Nested) -> StorageClass rules=_rules, fill_value=StructFillValue, fill_value_rules=_fill_value_rules, + fill_value_canonical=_fill_value_canonical, storage=_storage, ) """The `struct` data type: a record of named fields, each field's type a nested field.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/definition.py b/packages/zarr-metadata/src/zarr_metadata/v3/definition.py index 65e766a55b..5f112e6b18 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/definition.py @@ -203,6 +203,15 @@ def acme_lz4_rules( `fill_value_problems(data_type, value)` judges a fill value against a data 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 fill value may be spelled more ways than one -- `"NaN"` and +`"0x7fc00000"` are one `float32` -- so a data type says which spelling +is its value's own: `fill_value_canonical`, handed what the rules are +handed and a fill value they allow. Two fill values are one value of the +type exactly when their canonical spellings are written alike: the same +JSON, as `json.dumps` writes it, which `==` is not -- it takes `-0.0`, +a `float32` of its own, for `0.0`. `canonical_fill_value(data_type, +value)` spells one, and gives `UNSET` for a fill value with a problem; a +data type that says nothing of it spells each value as written. A data type says how its values are stored, too: `storage`, a function of its configuration and the fields it holds, giving a `StorageClass` -- @@ -330,6 +339,7 @@ def acme_lz4_rules( StorageClass, StorageTransformerDefinition, Unclaimed, + canonical_fill_value, canonical_of, canonicalize, chunk_grid_lengths, @@ -378,6 +388,7 @@ def acme_lz4_rules( "Unclaimed", "ValidationProblem", "ZarrV3MetadataFieldJSON", + "canonical_fill_value", "canonical_of", "canonicalize", "check", diff --git a/packages/zarr-metadata/tests/model/test_array.py b/packages/zarr-metadata/tests/model/test_array.py index 90a2510fd1..34fd225c69 100644 --- a/packages/zarr-metadata/tests/model/test_array.py +++ b/packages/zarr-metadata/tests/model/test_array.py @@ -24,6 +24,8 @@ ZarrV2ArrayMetadata, ZarrV2ArrayMetadataPartial, ZarrV3ArrayMetadata, + ZarrV3ConsolidatedMetadata, + ZarrV3GroupMetadata, is_array_metadata_v2, is_array_metadata_v3, is_group_metadata_v2, @@ -515,6 +517,147 @@ def test_a_model_is_what_its_document_says_not_how_it_is_spelled( assert ZarrV3ArrayMetadata.from_json(written) == model +_DATETIME = {"name": "numpy.datetime64", "configuration": {"unit": "s", "scale_factor": 1}} +_LITTLE = {"name": "bytes", "configuration": {"endian": "little"}} + + +@pytest.mark.parametrize( + ("data_type", "left", "right", "same"), + [ + ("float32", "NaN", "0x7fc00000", True), + ("float32", 1, 1.0, True), + ("float32", 0.1, 0.10000000149011612, True), + ("float32", 0.0, -0.0, False), + ("float32", "NaN", "0xffc00000", False), + (_DATETIME, "NaT", -(2**63), True), + ("bytes", [65], "QR==", True), + # The fill value of a data type nothing in scope claims is not + # interpreted, and is compared as JSON text. + ("acme.decimal", {"a": 1, "b": 2}, {"b": 2, "a": 1}, True), + ("acme.decimal", [1, 2], [2, 1], False), + ("acme.decimal", True, 1, False), + ("acme.decimal", 0.0, -0.0, False), + ], +) +def test_two_models_are_one_array_when_their_fill_values_are_one_value( + data_type: object, left: object, right: object, same: bool +) -> None: + """As two fields are one when they read the same, however each is spelled.""" + codecs = [{"name": "vlen-bytes"} if data_type == "bytes" else _LITTLE] + document = {**ZarrV3ArrayMetadata.create_default(shape=(2,)).to_json(), "codecs": codecs} + models = [ + ZarrV3ArrayMetadata.from_json({**document, "data_type": data_type, "fill_value": value}) + for value in (left, right) + ] + assert (models[0] == models[1]) is same + assert (models[1] == models[0]) is same + assert models[0] == ZarrV3ArrayMetadata.from_json(models[0].to_json()) + # Equal models hash alike. + if same: + assert hash(models[0]) == hash(models[1]) + # A group holding the arrays says so too. + groups = [ + ZarrV3GroupMetadata( + attributes={}, + consolidated_metadata=ZarrV3ConsolidatedMetadata(metadata={"a": model}), + extra_fields={}, + ) + for model in models + ] + assert (groups[0] == groups[1]) is same + + +_NOSHUFFLE = {"cname": "lz4", "clevel": 5, "shuffle": "noshuffle", "blocksize": 0} + + +@pytest.mark.parametrize( + ("member", "left", "right"), + [ + ( + "codecs", + [_LITTLE, {"name": "blosc", "configuration": _NOSHUFFLE}], + [_LITTLE, {"name": "blosc", "configuration": {**_NOSHUFFLE, "typesize": 4}}], + ), + ( + "codecs", + [_LITTLE, {"name": "zstd", "configuration": {"level": 1}}], + [_LITTLE, {"name": "zstd", "configuration": {"level": 1, "checksum": False}}], + ), + ( + "chunk_key_encoding", + "default", + {"name": "default", "configuration": {"separator": "/"}}, + ), + ], + ids=["blosc-typesize-noshuffle", "zstd-checksum-false", "default-separator"], +) +def test_two_models_are_one_array_when_their_fields_read_the_same( + member: str, left: object, right: object +) -> None: + """The spec's equivalences, which each definition's `canonical` folds, hold in a model's `==`, though `to_json` writes each as given.""" + document = ZarrV3ArrayMetadata.create_default(shape=(2,)).to_json() + models = [ZarrV3ArrayMetadata.from_json({**document, member: value}) for value in (left, right)] + assert models[0] == models[1] + assert hash(models[0]) == hash(models[1]) + assert models[0].to_json() != models[1].to_json() + + +@pytest.mark.parametrize( + ("left", "right", "same"), + [ + ({"a": math.nan}, {"a": math.nan}, True), + ({"a": 1, "b": 2}, {"b": 2, "a": 1}, True), + ({"a": True}, {"a": 1}, False), + ({"a": 0.0}, {"a": -0.0}, False), + ({"a": 1}, {"a": 1.0}, False), + ], + ids=["nan", "key-order", "bool-vs-int", "signed-zero", "int-vs-float"], +) +def test_user_json_compares_as_text( + left: "dict[str, JSONValue]", right: "dict[str, JSONValue]", same: bool +) -> None: + """Attributes, which nothing interprets, compare as a document writes them: `NaN` is itself, `true` is not `1`, `-0.0` is not `0.0`.""" + arrays = [ZarrV3ArrayMetadata.create_default(attributes=held) for held in (left, right)] + groups = [ + ZarrV3GroupMetadata(attributes=held, consolidated_metadata=UNSET, extra_fields={}) + for held in (left, right) + ] + v2 = [ZarrV2ArrayMetadata.create_default(attributes=held) for held in (left, right)] + for models in (arrays, groups, v2): + assert (models[0] == models[1]) is same + if same: + assert hash(models[0]) == hash(models[1]) + + +def test_a_model_holding_nan_user_data_equals_its_copies() -> None: + # What Python's `==` on the value denies: `nan != nan`. + model = ZarrV3ArrayMetadata.create_default(attributes={"_FillValue": math.nan}) + assert ZarrV3ArrayMetadata.from_key_value(model.to_key_value()) == model + assert pickle.loads(pickle.dumps(model)) == model + assert ZarrV3ArrayMetadata.from_json(json.loads(json.dumps(model.to_json()))) == model + + +@pytest.mark.parametrize( + ("left", "right", "same"), + [ + (0.0, 0.0, True), + ("NaN", "NaN", True), + (0.0, -0.0, False), + (1, 1.0, False), + (0, False, False), + ], +) +def test_two_v2_models_are_one_array_when_their_documents_are_written_alike( + left: object, right: object, same: bool +) -> None: + """A v2 data type is not interpreted, so nor is its fill value: the document as text decides.""" + model = ZarrV2ArrayMetadata.create_default(shape=(2,), chunks=(2,), dtype=" None: model = ZarrV3ArrayMetadata.create_default( codecs=( @@ -826,7 +969,7 @@ def test_metadata_field_must_understand_must_be_boolean(value: object) -> None: def test_metadata_field_rejects_unknown_envelope_member() -> None: """Unknown envelope keys cannot be silently discarded during normalization.""" problems = validate_metadata_field_v3({"name": "x", "typo": 1}) - assert [(problem.loc, problem.kind) for problem in problems] == [(("typo",), "invalid_value")] + assert [(problem.loc, problem.kind) for problem in problems] == [(("typo",), "unknown_key")] @pytest.mark.parametrize("field", ["codecs", "storage_transformers"]) diff --git a/packages/zarr-metadata/tests/model/test_construction.py b/packages/zarr-metadata/tests/model/test_construction.py index 8190d57859..29a29402ec 100644 --- a/packages/zarr-metadata/tests/model/test_construction.py +++ b/packages/zarr-metadata/tests/model/test_construction.py @@ -52,6 +52,7 @@ "metadata": { "x": ARRAY.to_json(), "y": {"zarr_format": 3, "node_type": "group"}, + "y/z": ARRAY.to_json(), }, }, } @@ -186,6 +187,15 @@ def counted( (GROUP, {"attributes": {1: "a"}}, [(("attributes",), "invalid_type")]), (GROUP, {"attributes": ()}, [(("attributes",), "invalid_type")]), (GROUP, {"extra_fields": {"acme": math.nan}}, [(("acme",), "invalid_value")]), + ( + GROUP.consolidated_metadata, + {"metadata": {"x": ARRAY, "x/a": ARRAY, "__b": ARRAY, "c/d": ARRAY}}, + [ + (("metadata", "__b"), "invalid_value"), + (("metadata", "x/a"), "invalid_value"), + (("metadata", "c"), "missing_key"), + ], + ), (V2_ARRAY, {"order": "Q"}, [(("order",), "invalid_value")]), (V2_ARRAY, {"chunks": (4, 4)}, [(("chunks",), "invalid_value")]), (V2_GROUP, {"attributes": {1: "a"}}, [(("attributes",), "invalid_type")]), @@ -206,6 +216,7 @@ def counted( "group-attribute-key", "group-attributes-empty-and-no-object", "group-extension-not-json", + "consolidated-paths", "v2-order", "v2-chunks-for-another-rank", "v2-group-attribute-key", diff --git a/packages/zarr-metadata/tests/model/test_group.py b/packages/zarr-metadata/tests/model/test_group.py index 27d05e603a..3542a3c24e 100644 --- a/packages/zarr-metadata/tests/model/test_group.py +++ b/packages/zarr-metadata/tests/model/test_group.py @@ -57,6 +57,7 @@ Nested, Refused, Unclaimed, + resolve, ) from zarr_metadata.v3.group import ZarrV3GroupMetadataJSONPartial @@ -157,11 +158,58 @@ def test_group_zarr_format_rejects_float( assert [(p.loc, p.kind) for p in validate(document)] == [(("zarr_format",), "invalid_value")] -def test_group_v2_rejects_unknown_document_member() -> None: - """The closed v2 merged-document shape rejects undeclared members.""" - assert [(p.loc, p.kind) for p in validate_group_metadata_v2({"zarr_format": 2, "x": 1})] == [ - (("x",), "invalid_value") - ] +def _v2_consolidated_problems(document: object) -> list[tuple[tuple[str | int, ...], str]]: + with pytest.raises(MetadataValidationError) as raised: + ZarrV2ConsolidatedMetadata.from_json(document) + return [(p.loc, p.kind) for p in raised.value.problems] + + +def _v3_field_problems(field: object) -> list[tuple[tuple[str | int, ...], str]]: + return [(p.loc, p.kind) for p in resolve(field, CodecDefinition, CORE_AND_EXTENSIONS)[1]] + + +@pytest.mark.parametrize( + ("problems", "expected"), + [ + ( + lambda: [ + (p.loc, p.kind) for p in validate_group_metadata_v2({"zarr_format": 2, "x": 1}) + ], + [(("x",), "unknown_key")], + ), + ( + lambda: _v2_consolidated_problems( + {"zarr_consolidated_format": 1, "metadata": {}, "x": 1} + ), + [(("x",), "unknown_key")], + ), + ( + lambda: [ + (p.loc, p.kind) + for p in validate_group_metadata_v3( + _group(consolidated_metadata={**_inline(), "x": 1}) + ) + ], + [(("consolidated_metadata", "x"), "unknown_key")], + ), + ( + lambda: _v3_field_problems({"name": "gzip", "configuration": {"level": 1}, "x": 1}), + [(("x",), "unknown_key")], + ), + ( + lambda: _v3_field_problems({"name": "gzip", "configuration": {"level": 1, "x": 1}}), + [(("configuration", "x"), "unknown_key")], + ), + ], + ids=["v2-group", "v2-consolidated", "v3-consolidated", "v3-field", "v3-configuration"], +) +def test_a_member_a_closed_object_does_not_declare_is_an_unknown_key( + problems: Callable[[], list[tuple[tuple[str | int, ...], str]]], + expected: list[tuple[tuple[str | int, ...], str]], +) -> None: + # Wherever it sits, so a reader that tolerates what another writer + # added -- NCZarr's `_nczarr_*` keys -- filters by kind. + assert problems() == expected @pytest.mark.parametrize( @@ -254,7 +302,7 @@ def test_v2_group_from_key_value_rejects_zgroup_extra_members(extra_key: str) -> ZarrV2GroupMetadata.from_key_value({".zgroup": json.dumps(doc).encode()}) assert [(problem.loc, problem.kind) for problem in exc_info.value.problems] == [ - ((extra_key,), "invalid_value") + ((extra_key,), "unknown_key") ] @@ -453,19 +501,35 @@ def _fields_of_an_array(*at: str | int) -> list[tuple[str | int, ...]]: ["a", "g"], _fields_of_an_array(*A), ), - # A group's consolidated metadata in a group's: each field located - # from the root of the outer document. + # Every node below the group, each below a group, at its path. + ( + _group(consolidated_metadata=_inline(g=_group(), **{"g/b": _array()})), + ["g", "g/b"], + _fields_of_an_array("consolidated_metadata", "metadata", "g/b"), + ), + # A group's consolidated metadata in a group's, listing what the group + # lists too: each field located from the root of the outer document. ( _group( - consolidated_metadata=_inline(g=_group(consolidated_metadata=_inline(b=_array()))) - ), - ["g"], - _fields_of_an_array( - "consolidated_metadata", "metadata", "g", "consolidated_metadata", "metadata", "b" + consolidated_metadata=_inline( + g=_group(consolidated_metadata=_inline(b=_array())), **{"g/b": _array()} + ) ), + ["g", "g/b"], + [ + *_fields_of_an_array( + "consolidated_metadata", + "metadata", + "g", + "consolidated_metadata", + "metadata", + "b", + ), + *_fields_of_an_array("consolidated_metadata", "metadata", "g/b"), + ], ), ], - ids=["no-consolidated-metadata", "null", "an-array-and-a-group", "nested"], + ids=["no-consolidated-metadata", "null", "an-array-and-a-group", "paths", "nested"], ) def test_a_group_reads_each_document_its_consolidated_metadata_holds( document: dict[str, object], paths: list[str], locs: list[tuple[str | int, ...]] @@ -483,6 +547,166 @@ def test_a_group_reads_each_document_its_consolidated_metadata_holds( assert all(held[path] is reading.consolidated[path].metadata for path in paths) +@pytest.mark.parametrize( + ("path", "fault"), + [ + ("", "is the group's own"), + ("/a", 'starts with "/"'), + ("a/", 'ends with "/"'), + ("a//b", 'holds an empty name between two "/"'), + (".", 'holds ".", a name that is periods alone'), + ("a/../b", 'holds "..", a name that is periods alone'), + ("__a", 'holds "__a", a name that starts with the reserved "__"'), + ("zarr.json", 'holds "zarr.json", a name that is the reserved "zarr.json"'), + ], +) +def test_error_a_document_in_consolidated_metadata_is_at_a_node_s_path_below_the_group( + path: str, fault: str +) -> None: + # Its node names, joined by "/", as the reference implementation keeps + # it: the group's own path, "/", and it make the node's. + document = _group(consolidated_metadata=_inline(**{path: _group()})) + message = f"expected the path of a node below the group, got {json.dumps(path)}, which {fault}" + assert validate_group_metadata_v3(document) == ( + ValidationProblem(("consolidated_metadata", "metadata", path), message, "invalid_value"), + ) + + +@pytest.mark.parametrize( + ("documents", "path"), + [ + ({"a": _array(), "a/b": _group()}, "a/b"), + # However many groups are missing between them: none would help. + ({"a": _array(), "a/b/c": _array()}, "a/b/c"), + ], + ids=["child", "descendant"], +) +def test_error_no_document_in_consolidated_metadata_is_below_an_array( + documents: dict[str, object], path: str +) -> None: + # "Group nodes may have children but array nodes may not." A message + # names each node by its path in the hierarchy below the group. + document = _group(consolidated_metadata=_inline(**documents)) + message = f'expected a node below a group, got "/{path}", below the array "/a"' + assert validate_group_metadata_v3(document) == ( + ValidationProblem(("consolidated_metadata", "metadata", path), message, "invalid_value"), + ) + + +def test_a_document_of_no_node_type_is_taken_as_a_group_s() -> None: + # Its own problem is reported where it sits, and the nodes below it are + # not refused for it. + document = _group( + consolidated_metadata=_inline(a={"zarr_format": 3, "node_type": "x"}, **{"a/b": _array()}) + ) + assert [(p.loc, p.kind) for p in validate_group_metadata_v3(document)] == [ + (("consolidated_metadata", "metadata", "a", "node_type"), "invalid_value") + ] + + +def test_error_consolidated_metadata_holds_the_group_holding_each_document() -> None: + # The nearest group missing above a node, once, counting those above it + # up to the group holding the documents. + document = _group(consolidated_metadata=_inline(**{"a/b/c": _array(), "a/b/d": _array()})) + assert [(p.loc, p.message, p.kind) for p in validate_group_metadata_v3(document)] == [ + ( + ("consolidated_metadata", "metadata", "a/b"), + 'missing the group holding "/a/b/c", and 1 group above it', + "missing_key", + ), + ] + + +def test_error_a_consolidated_metadata_key_that_is_not_a_string() -> None: + listing: dict[object, object] = {"a": _array(), 1: _array()} + document = _group(consolidated_metadata={**_inline(), "metadata": listing}) + assert [(p.loc, p.kind) for p in validate_group_metadata_v3(document)] == [ + (("consolidated_metadata", "metadata"), "invalid_type") + ] + + +NESTED = ("consolidated_metadata", "metadata", "g", "consolidated_metadata", "metadata") +"""Where the own listing of the group at `g` sits in the outer document.""" + + +@pytest.mark.parametrize( + ("listed", "flat", "expected"), + [ + # What a listed group lists itself is what the group lists, too. + ({"b": _array()}, {"g/b": _array()}, []), + # A node the listed group lists alone would be dropped by the + # reference reader, which keeps the flat listing. + ( + {"b": _array()}, + {}, + [ + ( + (*NESTED, "b"), + 'expected a node the group lists, got "/g/b", which "/g" lists alone', + "invalid_value", + ) + ], + ), + # Nor may the two listings disagree on what a node is. + ( + {"b": _array()}, + {"g/b": _group()}, + [ + ( + (*NESTED, "b"), + 'expected a group, as the group lists "/g/b", got an array', + "invalid_value", + ) + ], + ), + # A deeper listing is the listed group's own to judge, when its + # document is read: its problem is that document's, at its place. + ( + {"h": _group(consolidated_metadata=_inline(x=_array()))}, + {"g/h": _group()}, + [ + ( + (*NESTED, "h", "consolidated_metadata", "metadata", "x"), + 'expected a node the group lists, got "/h/x", which "/h" lists alone', + "invalid_value", + ) + ], + ), + ], + ids=["agreeing", "listed-alone", "contradicting", "deeper"], +) +def test_a_listed_group_s_own_listing_lists_what_the_group_lists( + listed: dict[str, object], + flat: dict[str, object], + expected: list[tuple[tuple[str, ...], str, str]], +) -> None: + document = _group( + consolidated_metadata=_inline(g=_group(consolidated_metadata=_inline(**listed)), **flat) + ) + problems = validate_group_metadata_v3(document) + assert [(p.loc, p.message, p.kind) for p in problems] == expected + # The constructor refuses what the reader reports, built of models: a + # listed group whose own listing is wrong is refused as it is built. + listing = {"g": _group(consolidated_metadata=_inline(**listed)), **flat} + deeper = [(loc, message, kind) for loc, message, kind in expected if len(loc) > len(NESTED) + 1] + if len(deeper) != 0: + with pytest.raises(MetadataValidationError) as inner: + node_metadata_from_json_v3(listing["g"]) + assert [(p.loc, p.message, p.kind) for p in inner.value.problems] == [ + (loc[3:], message, kind) for loc, message, kind in deeper + ] + return + members = {key: node_metadata_from_json_v3(value) for key, value in listing.items()} + if expected == []: + assert ZarrV3ConsolidatedMetadata(metadata=members).metadata.keys() == members.keys() + return + with pytest.raises(MetadataValidationError) as raised: + ZarrV3ConsolidatedMetadata(metadata=members) + assert [(p.loc[1:], p.message, p.kind) for p in raised.value.problems] == [ + (loc[2:], message, kind) for loc, message, kind in expected + ] + + def test_each_document_its_consolidated_metadata_holds_is_read_once() -> None: reads: list[GzipCodecConfiguration] = [] @@ -581,7 +805,7 @@ def test_a_node_is_read_as_the_node_its_node_type_says( ids=["another-kind", "a-number", "null"], ) def test_error_a_node_type_the_spec_does_not_define(node_type: object, kind: str) -> None: - """Nothing else of the document is read, so nothing else is judged.""" + """Nothing else of the document is read but its `zarr_format`, which is 3 here, so nothing else is judged.""" read = read_node_metadata_v3({**_array(), "node_type": node_type, "shape": "not a shape"}) assert isinstance(read, ZarrV3UnknownNodeReading) assert [(p.loc, p.kind) for p in read.problems] == [(("node_type",), kind)] @@ -596,6 +820,41 @@ def test_error_a_document_without_a_node_type() -> None: assert [(p.loc, p.kind) for p in read.problems] == [(("node_type",), "missing_key")] +@pytest.mark.parametrize( + ("document", "problems"), + [ + # zarr-python 2's draft of v3 (zarr-python#2982): a root `zarr.json` + # naming its format by URL, and no node type. + ( + { + "zarr_format": "https://purl.org/zarr/spec/protocol/core/3.0", + "metadata_encoding": "https://purl.org/zarr/spec/protocol/core/3.0", + "metadata_key_suffix": ".json", + "extensions": [], + }, + [(("zarr_format",), "invalid_type"), (("node_type",), "missing_key")], + ), + ( + {"zarr_format": 2, "shape": [4], "chunks": [4], "dtype": "|u1"}, + [(("zarr_format",), "invalid_value"), (("node_type",), "missing_key")], + ), + ( + {"node_type": "dataset"}, + [(("zarr_format",), "missing_key"), (("node_type",), "invalid_value")], + ), + ], + ids=["v3-draft", "v2", "no-format"], +) +def test_error_a_document_of_another_format_says_so( + document: dict[str, object], problems: list[tuple[tuple[str | int, ...], str]] +) -> None: + read = read_node_metadata_v3(document) + assert isinstance(read, ZarrV3UnknownNodeReading) + assert [(p.loc, p.kind) for p in read.problems] == problems + # The validator reads a node's type as the reader does. + assert [(p.loc, p.kind) for p in validate_node_metadata_v3(document)] == problems + + def test_error_a_node_that_is_not_an_object() -> None: read = read_node_metadata_v3([_array()]) assert isinstance(read, ZarrV3UnknownNodeReading) diff --git a/packages/zarr-metadata/tests/test_problem_data.py b/packages/zarr-metadata/tests/test_problem_data.py index f6c1bfa026..9541756ed0 100644 --- a/packages/zarr-metadata/tests/test_problem_data.py +++ b/packages/zarr-metadata/tests/test_problem_data.py @@ -34,6 +34,8 @@ validate_json, validate_metadata_field_v3, validate_node_metadata_v3, + validate_node_name_v3, + validate_node_path_v3, ) from zarr_metadata.typed_json import check from zarr_metadata.v3.codec.gzip import GZIP_CODEC @@ -223,6 +225,8 @@ def _raised(read: Callable[[], object]) -> Sequence[ValidationProblem]: validate_metadata_field_v3, {"name": 1, "configuration": {"a": [math.nan]}, "extra": [1]}, ), + (validate_node_name_v3, "__/"), + (validate_node_path_v3, "a//"), (validate_array_metadata_v3, BAD_ARRAY), (lambda value: read_array_metadata_v3(value).problems, BAD_ARRAY), (lambda value: _raised(lambda: parse_array_metadata_v3(value)), BAD_ARRAY), @@ -236,7 +240,7 @@ def _raised(read: Callable[[], object]) -> Sequence[ValidationProblem]: "consolidated_metadata": { "kind": "inline", "must_understand": [False], - "metadata": {"a": BAD_ARRAY}, + "metadata": {"a": BAD_ARRAY, "__b": BAD_ARRAY, "a/c": BAD_ARRAY, "d/e": BAD_ARRAY}, }, }, ), @@ -266,6 +270,8 @@ def _raised(read: Callable[[], object]) -> Sequence[ValidationProblem]: "fill-value-problems", "validate-json", "validate-metadata-field", + "validate-node-name", + "validate-node-path", "validate-array", "read-array", "parse-array", diff --git a/packages/zarr-metadata/tests/test_public_api.py b/packages/zarr-metadata/tests/test_public_api.py index 82448e356c..03e98d268f 100644 --- a/packages/zarr-metadata/tests/test_public_api.py +++ b/packages/zarr-metadata/tests/test_public_api.py @@ -291,6 +291,8 @@ def test_all_is_grouped_and_unique() -> None: "Lengths", "Loc", "Nested", + "NodeName", + "NodePath", # What a scope made of a field: `Read` by the definition that claims # its name, `Unclaimed`, or `Refused`; `Resolved` is the three. "Read", diff --git a/packages/zarr-metadata/tests/v3/test_definitions.py b/packages/zarr-metadata/tests/v3/test_definitions.py index a262f152d8..3477e66be8 100644 --- a/packages/zarr-metadata/tests/v3/test_definitions.py +++ b/packages/zarr-metadata/tests/v3/test_definitions.py @@ -42,6 +42,7 @@ Unclaimed, ValidationProblem, ZarrV3MetadataFieldJSON, + canonical_of, check, configuration_of, resolve, @@ -898,6 +899,23 @@ def test_error_check_judges_a_nested_envelope() -> None: assert [found.loc for found in problems] == [("codecs", 0, "configuration")] +def test_judge_leaves_out_a_member_a_nested_field_s_envelope_does_not_declare() -> None: + # Reported as an unknown key and left out, as the checker leaves out a + # key a closed TypedDict does not declare: the configuration comes back. + for given in (ACME_STACK.check, ACME_STACK.judge): + typed, problems = given({"codecs": [{"name": "crc32c", "x": 1}]}) + assert typed == {"codecs": ({"name": "crc32c"},)} + assert _locs(problems) == [(("codecs", 0, "x"), "unknown_key")] + + +def test_error_judge_refuses_a_nested_field_that_need_not_be_understood() -> None: + # A `must_understand` of false is no unknown key: the configuration + # does not come back. + typed, problems = ACME_STACK.judge({"codecs": [{"name": "crc32c", "must_understand": False}]}) + assert typed is None + assert _locs(problems) == [(("codecs", 0, "must_understand"), "invalid_value")] + + def test_judge_is_the_check_and_then_the_rules() -> None: # A caller holding one configuration: the rules are asked only of a # configuration that type-checked, so they never meet a wrong type. @@ -941,6 +959,7 @@ def test_a_scope_pickles_as_its_definitions_and_copies_as_itself() -> None: LE: Final = {"name": "bytes", "configuration": {"endian": "little"}} SHARD: Final = {"chunk_shape": [2], "codecs": [LE], "index_location": "end"} +NOSHUFFLE: Final = {"cname": "lz4", "clevel": 5, "shuffle": "noshuffle", "blocksize": 0} @pytest.mark.parametrize( @@ -980,6 +999,71 @@ def test_a_scope_pickles_as_its_definitions_and_copies_as_itself() -> None: False, ), ("int8", "uint8", DataTypeDefinition, False), + # The spec's equivalences, which each definition's `canonical` + # folds: a member at its default, a run-length encoding, leading + # zeros in a size. + ( + {"name": "blosc", "configuration": {**NOSHUFFLE}}, + {"name": "blosc", "configuration": {**NOSHUFFLE, "typesize": 4}}, + CodecDefinition, + True, + ), + ( + "default", + {"name": "default", "configuration": {"separator": "/"}}, + ChunkKeyEncodingDefinition, + True, + ), + ( + "default", + {"name": "default", "configuration": {"separator": "."}}, + ChunkKeyEncodingDefinition, + False, + ), + ( + {"name": "v2"}, + {"name": "v2", "configuration": {"separator": "."}}, + ChunkKeyEncodingDefinition, + True, + ), + ( + { + "name": "sharding_indexed", + "configuration": {**SHARD, "index_codecs": [LE, "crc32c"]}, + }, + { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": [2], + "codecs": [LE], + "index_codecs": [LE, "crc32c"], + }, + }, + CodecDefinition, + True, + ), + ( + {"name": "zstd", "configuration": {"level": 3}}, + {"name": "zstd", "configuration": {"level": 3, "checksum": False}}, + CodecDefinition, + True, + ), + ( + {"name": "zstd", "configuration": {"level": 3}}, + {"name": "zstd", "configuration": {"level": 3, "checksum": True}}, + CodecDefinition, + False, + ), + ( + {"name": "rectilinear", "configuration": {"kind": "inline", "chunk_shapes": [[2, 2]]}}, + { + "name": "rectilinear", + "configuration": {"kind": "inline", "chunk_shapes": [[[2, 2]]]}, + }, + ChunkGridDefinition, + True, + ), + ("r008", "r8", DataTypeDefinition, True), ], ids=[ "bare-or-object", @@ -990,18 +1074,29 @@ def test_a_scope_pickles_as_its_definitions_and_copies_as_itself() -> None: "another-configuration", "unclaimed-another-configuration", "another-name", + "blosc-typesize-noshuffle", + "default-separator", + "default-other-separator", + "v2-separator", + "sharding-index-location", + "zstd-checksum-false", + "zstd-checksum-true", + "rectilinear-rle", + "raw-bits-leading-zeros", ], ) def test_two_fields_are_equal_when_they_read_the_same( one: JSONValue, other: JSONValue, kind: type[Definition[Any]], equal: bool ) -> None: - """However each was spelled; each is written as it reads, and equal fields are written the same.""" + """However each was spelled: equal fields have one simplest spelling and one hash, though each is written as read.""" first, _ = resolve(one, kind, CORE_AND_EXTENSIONS) second, _ = resolve(other, kind, CORE_AND_EXTENSIONS) assert isinstance(first, (Read, Unclaimed)) assert isinstance(second, (Read, Unclaimed)) assert (first == second) is equal - assert (first.to_json() == second.to_json()) is equal + assert (canonical_of(first, ()) == canonical_of(second, ())) is equal + if equal: + assert hash(first) == hash(second) def test_a_field_copied_or_pickled_is_read_by_a_definition_equal_to_its_own() -> None: diff --git a/packages/zarr-metadata/tests/v3/test_every_definition.py b/packages/zarr-metadata/tests/v3/test_every_definition.py index 5744860327..e7138ba75c 100644 --- a/packages/zarr-metadata/tests/v3/test_every_definition.py +++ b/packages/zarr-metadata/tests/v3/test_every_definition.py @@ -260,6 +260,39 @@ def test_every_example_reads_and_its_simplest_spelling_is_stable(key: str, field "configuration": {"kind": "inline", "chunk_shapes": (((32, 3), 16), 8)}, }, ), + # A member at its spec default is left out: a key encoding's + # separator, a shard's index location, zstd's checksum. + ({"name": "default", "configuration": {"separator": "/"}}, {"name": "default"}), + ({"name": "v2", "configuration": {"separator": "."}}, {"name": "v2"}), + ( + { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": [2], + "codecs": ["bytes"], + "index_codecs": [ + {"name": "bytes", "configuration": {"endian": "little"}}, + "crc32c", + ], + "index_location": "end", + }, + }, + { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": (2,), + "codecs": ({"name": "bytes"},), + "index_codecs": ( + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "crc32c"}, + ), + }, + }, + ), + ( + {"name": "zstd", "configuration": {"level": 3, "checksum": False}}, + {"name": "zstd", "configuration": {"level": 3}}, + ), ], ids=[ "blosc-noshuffle", @@ -268,10 +301,19 @@ def test_every_example_reads_and_its_simplest_spelling_is_stable(key: str, field "sharding-nested", "cast-value-target", "rectilinear-rle", + "default-separator", + "v2-separator", + "sharding-index-location", + "zstd-checksum", ], ) def test_the_simplest_spelling(field: dict[str, Any], simplest: object) -> None: - kinds = {"rectilinear": ChunkGridDefinition, "int8": DataTypeDefinition} + kinds = { + "rectilinear": ChunkGridDefinition, + "int8": DataTypeDefinition, + "default": ChunkKeyEncodingDefinition, + "v2": ChunkKeyEncodingDefinition, + } kind = kinds.get(field["name"], CodecDefinition) assert canonicalize(field, kind, CORE_AND_EXTENSIONS) == (simplest, ()) assert canonical_of(*resolve(field, kind, CORE_AND_EXTENSIONS)) == simplest @@ -384,7 +426,7 @@ def _shard(codecs: list[object], index_codecs: list[object]) -> dict[str, object ( {"name": "zfpy", "configuration": {}, "extra": 1}, CodecDefinition, - [(("extra",), "invalid_value")], + [(("extra",), "unknown_key")], ), (None, CodecDefinition, [((), "invalid_type")]), ( diff --git a/packages/zarr-metadata/tests/v3/test_fill_values.py b/packages/zarr-metadata/tests/v3/test_fill_values.py index 7963d08d24..7334bbcc82 100644 --- a/packages/zarr-metadata/tests/v3/test_fill_values.py +++ b/packages/zarr-metadata/tests/v3/test_fill_values.py @@ -8,15 +8,21 @@ from __future__ import annotations +import dataclasses +import json import math -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, cast, get_args import pytest +from hypothesis import given +from hypothesis import strategies as st from typing_extensions import TypedDict from zarr_metadata._json import value_at +from zarr_metadata._sentinel import UNSET from zarr_metadata.model import validate_array_metadata_v3, validate_group_metadata_v3 from zarr_metadata.model._array import ZarrV3ArrayMetadata +from zarr_metadata.v3.data_type._float import FloatWidth, float_bits from zarr_metadata.v3.data_type.struct import STRUCT_DATA_TYPE from zarr_metadata.v3.definition import ( CORE_AND_EXTENSIONS, @@ -26,6 +32,7 @@ Nested, Read, ValidationProblem, + canonical_fill_value, fill_value_problems, resolve, ) @@ -315,3 +322,148 @@ def test_a_struct_read_without_its_field_types_leaves_its_fields_unjudged() -> N json=STRUCT, name="struct", definition=STRUCT_DATA_TYPE, configuration=configuration ) assert fill_value_problems(struct, {"a": 300}) == () + + +# --- canonical spellings --------------------------------------------------- + + +def _alike(left: object, right: object) -> bool: + """Whether two JSON values are written alike: `==` takes `-0.0` for `0.0`.""" + return json.dumps(left, sort_keys=True) == json.dumps(right, sort_keys=True) + + +def _read(data_type: JSONValue) -> Read[DataTypeDefinition[Any]]: + resolved, found = resolve(data_type, DataTypeDefinition, CORE_AND_EXTENSIONS) + assert found == () + assert isinstance(resolved, Read) + return resolved + + +@pytest.mark.parametrize( + ("data_type", "spellings", "canonical"), + [ + ("float32", ["NaN", "0x7fc00000", "0x7FC00000"], "NaN"), + # Any other NaN is its bits: the spec names the one. + ("float32", ["0xffc00000"], "0xffc00000"), + ("float32", ["0x7fc00001", "0x7FC00001"], "0x7fc00001"), + ("float32", ["Infinity", "0x7f800000", 3.5e38, 10**39], "Infinity"), + ("float32", ["-Infinity", "0xff800000", -(10**39)], "-Infinity"), + ("float32", [0, 0.0, "0x00000000", 1e-46], 0.0), + # Zero's sign is a value of its own. + ("float32", [-0.0, "0x80000000"], -0.0), + ("float32", [1, 1.0, "0x3f800000"], 1.0), + # The number of the fewest digits that rounds to the value. + ("float32", [0.1, 0.10000000149011612, "0x3dcccccd"], 0.1), + # A number is read as a float64, as a JSON parser reads one, and + # then rounded to the type, as numpy rounds it: an integer and a + # number with a fraction that read as one float64 are one value. + ("float32", [2**53 + 2**29 + 1, 9007199791611905.0, 2**53], 9007199000000000.0), + # Of the numbers of the fewest digits, the one past the nearest: at + # a power of two, those that round to it reach further above it. + ("float16", [0.015625, "0x2400"], 0.01563), + ("float32", ["0x6b000000"], 1.5474251e26), + ("float16", [65504, 65519, "0x7bff"], 65500.0), + ("float16", [65520, "Infinity", "0x7c00"], "Infinity"), + # Halfway rounds to the even value. + ("float16", [2049, 2048], 2048.0), + ("float16", [2051, 2052], 2052.0), + ("float16", ["NaN", "0x7e00", "0x7E00"], "NaN"), + ("float16", [-0.0, "0x8000"], -0.0), + ("float64", [2**53 + 1, 2**53], float(2**53)), + ("float64", [10**400, "Infinity", "0x7ff0000000000000"], "Infinity"), + ("float64", [-(10**400), "-Infinity", "0xfff0000000000000"], "-Infinity"), + ("float64", ["NaN", "0x7ff8000000000000"], "NaN"), + ("complex64", [["NaN", -0.0], ["0x7fc00000", "0x80000000"]], ("NaN", -0.0)), + ("complex128", [[0.1, 1], ["0x3fb999999999999a", 1.0]], (0.1, 1.0)), + ("bytes", [[65], "QQ==", "QR=="], "QQ=="), + ("bytes", [[], ""], ""), + (DATETIME, ["NaT", -(2**63)], "NaT"), + (TIMEDELTA, ["NaT", -(2**63)], "NaT"), + (TIMEDELTA, [5], 5), + (STRUCT, [{"a": 1, "b": "0x7fc00000"}, {"b": "NaN", "a": 1}], {"a": 1, "b": "NaN"}), + # A field type nothing in scope claims spells its fill value as written. + ( + { + "name": "struct", + "configuration": {"fields": [{"name": "a", "data_type": "acme.decimal"}]}, + }, + [{"a": -0.0}], + {"a": -0.0}, + ), + # A type that spells each value one way spells it as written. + ("int8", [-128], -128), + ("bool", [True], True), + ("string", ["NaN"], "NaN"), + ("r16", [[0, 1]], (0, 1)), + ], +) +def test_a_fill_value_s_canonical_spelling_is_its_value_s( + data_type: JSONValue, spellings: list[object], canonical: JSONValue +) -> None: + read = _read(data_type) + for spelling in spellings: + spelled = canonical_fill_value(read, spelling) + assert _alike(spelled, canonical), (spelling, spelled) + # A fill value of the type, spelled as itself. + assert fill_value_problems(read, canonical) == () + assert _alike(canonical_fill_value(read, canonical), canonical) + + +def test_a_data_type_nothing_in_scope_claims_spells_a_fill_value_as_written() -> None: + unclaimed, _ = resolve("acme.decimal", DataTypeDefinition, CORE_AND_EXTENSIONS) + values: list[JSONValue] = [-0.0, True, 1, [1.0], None] + for value in values: + assert _alike(canonical_fill_value(unclaimed, value), value) + + +WIDTHS: tuple[FloatWidth, ...] = get_args(FloatWidth) + + +@given(st.data()) +def test_a_float_s_canonical_spelling_spells_its_bits(data: st.DataObject) -> None: + # Every value of each float type, NaNs among them: its canonical + # spelling is a fill value of the type, spelling the same bits, and + # its own canonical spelling. + width = data.draw(st.sampled_from(WIDTHS)) + bits = data.draw(st.integers(0, 2**width - 1)) + read = _read(f"float{width}") + spelled = canonical_fill_value(read, f"0x{bits:0{width // 4}x}") + assert spelled is not None + assert fill_value_problems(read, spelled) == () + assert float_bits(cast("float | str", spelled), width) == bits + assert _alike(canonical_fill_value(read, spelled), spelled) + + +def test_error_a_fill_value_with_a_problem_has_no_canonical_spelling() -> None: + # `UNSET`, since `None` is the JSON null, a fill value of a data type + # the scope did not read. + assert canonical_fill_value(_read("float32"), "0x7fc0") is UNSET + assert canonical_fill_value(_read("int8"), 1.0) is UNSET + assert canonical_fill_value(_read("int8"), math.nan) is UNSET + unclaimed, _ = resolve("acme.decimal", DataTypeDefinition, CORE_AND_EXTENSIONS) + assert canonical_fill_value(unclaimed, None) is None + + +def test_error_a_canonical_spelling_that_raises_says_which_data_type_raised_it() -> None: + def refuses(configuration: EmptyConfiguration, nested: Nested, value: object) -> JSONValue: + raise ValueError("no") + + scope = CORE_AND_EXTENSIONS.extended_with( + dataclasses.replace(ACME_POINT, fill_value_canonical=refuses) + ) + resolved, _ = resolve("acme.point", DataTypeDefinition, scope) + with pytest.raises(ValueError, match="no") as raised: + canonical_fill_value(resolved, {"x": 1}) + assert raised.value.__notes__ == ["raised by the fill_value_canonical of 'acme.point'"] + + +def test_error_a_canonical_spelling_that_is_not_json_is_refused() -> None: + def not_json(configuration: EmptyConfiguration, nested: Nested, value: object) -> JSONValue: + return cast("JSONValue", {1, 2}) + + scope = CORE_AND_EXTENSIONS.extended_with( + dataclasses.replace(ACME_POINT, fill_value_canonical=not_json) + ) + resolved, _ = resolve("acme.point", DataTypeDefinition, scope) + with pytest.raises(TypeError, match="'acme.point': its fill_value_canonical gives JSON"): + canonical_fill_value(resolved, {"x": 1}) diff --git a/packages/zarr-metadata/tests/v3/test_hierarchy.py b/packages/zarr-metadata/tests/v3/test_hierarchy.py new file mode 100644 index 0000000000..4b9944bf2b --- /dev/null +++ b/packages/zarr-metadata/tests/v3/test_hierarchy.py @@ -0,0 +1,256 @@ +"""A Zarr v3 hierarchy: the names and paths of its nodes, and the tree they make, as the core specification constrains them. + +Names: +https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/core/index.rst#L818-L837 +Paths: +https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/core/index.rst#L211-L229 +The tree: +https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/core/index.rst#L177-L181 +""" + +from __future__ import annotations + +import time +from typing import TYPE_CHECKING, Literal, cast + +import pytest + +from zarr_metadata.model import ( + MetadataValidationError, + ValidationProblem, + is_node_name_v3, + is_node_path_v3, + parse_node_name_v3, + parse_node_path_v3, + validate_node_name_v3, + validate_node_path_v3, +) +from zarr_metadata.v3._hierarchy import hierarchy_problems + +if TYPE_CHECKING: + from collections.abc import Callable + + +@pytest.mark.parametrize( + ("value", "message"), + [ + # The root's name, and names of any code points but the reserved. + ("", None), + ("a", None), + ("FOO", None), + ("a.b", None), + ("...a", None), + ("_a", None), + ("a__", None), + ("zarr.json.bak", None), + ("ñ", None), + ("/", 'expected a node name, got "/", which holds "/"'), + ("a/b", 'expected a node name, got "a/b", which holds "/"'), + (".", 'expected a node name, got ".", which is periods alone'), + ("..", 'expected a node name, got "..", which is periods alone'), + ("__a", 'expected a node name, got "__a", which starts with the reserved "__"'), + ("zarr.json", 'expected a node name, got "zarr.json", which is the reserved "zarr.json"'), + # Every reason a name is not one, in one problem. + ( + "__/", + 'expected a node name, got "__/", which holds "/" and starts with the reserved "__"', + ), + ], +) +def test_node_names(value: str, message: str | None) -> None: + problems = validate_node_name_v3(value) + assert [problem.message for problem in problems] == ([] if message is None else [message]) + assert {(problem.loc, problem.kind, problem.input) for problem in problems} <= { + ((), "invalid_value", value) + } + assert is_node_name_v3(value) is (message is None) + if message is None: + assert parse_node_name_v3(value) == value + + +@pytest.mark.parametrize( + ("value", "message"), + [ + # The root's path, and the paths below it. + ("/", None), + ("/a", None), + ("/a/b", None), + ("/a/.b/c..", None), + ("", 'expected a node path, got "", which does not start with "/"'), + ("a/b", 'expected a node path, got "a/b", which does not start with "/"'), + ("/a/", 'expected a node path, got "/a/", which ends with "/"'), + ( + "//", + 'expected a node path, got "//", which ends with "/" and holds an empty name between two "/"', + ), + ("/a//b", 'expected a node path, got "/a//b", which holds an empty name between two "/"'), + ( + "/a/../b", + 'expected a node path, got "/a/../b", which holds "..", a name that is periods alone', + ), + ( + "/__a", + ( + 'expected a node path, got "/__a", which holds "__a", a name that starts with the ' + 'reserved "__"' + ), + ), + ( + "/a/zarr.json", + ( + 'expected a node path, got "/a/zarr.json", which holds "zarr.json", a name that is ' + 'the reserved "zarr.json"' + ), + ), + # Every reason a path is not one, in one problem: the first name that + # is not a node name is said, and the rest counted. + ( + "/./__a/", + ( + 'expected a node path, got "/./__a/", which ends with "/", holds ".", a name that is ' + "periods alone and holds 1 more name that is not a node name" + ), + ), + ], +) +def test_node_paths(value: str, message: str | None) -> None: + problems = validate_node_path_v3(value) + assert [problem.message for problem in problems] == ([] if message is None else [message]) + assert {(problem.loc, problem.kind, problem.input) for problem in problems} <= { + ((), "invalid_value", value) + } + assert is_node_path_v3(value) is (message is None) + if message is None: + assert parse_node_path_v3(value) == value + + +def test_error_parse_node_name_raises_every_reason_a_string_is_not_a_node_name() -> None: + with pytest.raises(MetadataValidationError) as raised: + parse_node_name_v3("__/") + assert raised.value.problems == validate_node_name_v3("__/") + assert len(raised.value.problems) == 1 + assert 'holds "/"' in raised.value.problems[0].message + assert 'starts with the reserved "__"' in raised.value.problems[0].message + + +def test_error_parse_node_path_raises_every_reason_a_string_is_not_a_node_path() -> None: + with pytest.raises(MetadataValidationError) as raised: + parse_node_path_v3("/./__a/") + assert raised.value.problems == validate_node_path_v3("/./__a/") + assert len(raised.value.problems) == 1 + assert 'ends with "/"' in raised.value.problems[0].message + assert "1 more name" in raised.value.problems[0].message + + +@pytest.mark.parametrize( + ("validate", "parse", "what"), + [ + (validate_node_name_v3, parse_node_name_v3, "a node name"), + (validate_node_path_v3, parse_node_path_v3, "a node path"), + ], + ids=["name", "path"], +) +def test_error_a_node_name_or_path_is_a_string( + validate: Callable[[object], tuple[ValidationProblem, ...]], + parse: Callable[[object], str], + what: str, +) -> None: + problems = validate(3) + assert problems == (ValidationProblem((), f"expected {what}, got 3", "invalid_type"),) + assert problems[0].input == 3 + with pytest.raises(MetadataValidationError) as raised: + parse(b"a") + assert [(problem.loc, problem.kind) for problem in raised.value.problems] == [ + ((), "invalid_type") + ] + + +@pytest.mark.parametrize( + "nodes", + [ + # No nodes, a root alone, and a tree of groups whose leaves are + # arrays; the root may be an array, which is then the hierarchy. + {}, + {"/": "group"}, + {"/": "array"}, + {"/": "group", "/a": "array", "/g": "group", "/g/b": "array", "/g/h": "group"}, + # A node of no type known is taken as a group. + {"/": "group", "/x": None, "/x/a": "array"}, + ], + ids=["empty", "root-group", "root-array", "tree", "unknown-type"], +) +def test_a_hierarchy(nodes: dict[str, Literal["array", "group"] | None]) -> None: + assert hierarchy_problems(nodes) == () + + +def test_error_a_hierarchy_holds_its_nodes_at_node_paths() -> None: + assert hierarchy_problems({"/": "group", "a": "array", "/b/": "array"}) == ( + ValidationProblem( + ("a",), 'expected a node path, got "a", which does not start with "/"', "invalid_value" + ), + ValidationProblem( + ("/b/",), 'expected a node path, got "/b/", which ends with "/"', "invalid_value" + ), + ) + + +@pytest.mark.parametrize( + ("nodes", "path"), + [ + ({"/": "group", "/a": "array", "/a/b": "group"}, "/a/b"), + # However many groups are missing between them: none would help. + ({"/": "group", "/a": "array", "/a/b/c": "array"}, "/a/b/c"), + # The root is an array: the hierarchy is that array alone. + ({"/": "array", "/a": "group"}, "/a"), + ], + ids=["child", "descendant", "below-the-root"], +) +def test_error_no_node_is_below_an_array( + nodes: dict[str, Literal["array", "group"] | None], path: str +) -> None: + holder = next(ancestor for ancestor in ("/a", "/") if nodes.get(ancestor) == "array") + message = f'expected a node below a group, got "{path}", below the array "{holder}"' + assert hierarchy_problems(nodes) == (ValidationProblem((path,), message, "invalid_value"),) + + +def test_error_a_hierarchy_holds_the_group_holding_each_node() -> None: + # The nearest group missing above a node, once, counting those above it: + # the root's among them. + assert hierarchy_problems({"/a/b/c": "array", "/a/b/d": "array"}) == ( + ValidationProblem( + ("/a/b",), 'missing the group holding "/a/b/c", and 2 groups above it', "missing_key" + ), + ) + assert hierarchy_problems({"/": "group", "/a/b": "array"}) == ( + ValidationProblem(("/a",), 'missing the group holding "/a/b"', "missing_key"), + ) + + +def test_problems_stay_proportional_to_the_path() -> None: + # One problem per value, however many names are wrong and however many + # groups are missing, so a hostile path costs what it weighs. + path = "/" * 10_000 + problems = validate_node_path_v3(path) + assert len(problems) == 1 + assert len(problems[0].message) < len(path) + 200 + deep = "/a" * 5_000 + found = hierarchy_problems({deep: "array"}) + assert [(problem.loc, problem.kind) for problem in found] == [ + ((deep.rpartition("/")[0],), "missing_key") + ] + assert found[0].message.endswith(", and 4999 groups above it") + assert len(found[0].message) < len(deep) + 200 + + +def test_a_hierarchy_is_walked_in_time_proportional_to_its_paths() -> None: + # Each path split once and walked name by name: a key of a million + # characters, and thousands of keys under one long missing prefix, + # each cost what they weigh, where walking up by ancestor strings + # costs the square. + started = time.perf_counter() + long = "/a" * 500_000 + assert len(hierarchy_problems({long: "array"})) == 1 + prefix = "/a" * 5_000 + many = {f"{prefix}/{index}": "array" for index in range(2_000)} + assert len(hierarchy_problems(cast("dict[str, Literal['array', 'group'] | None]", many))) == 1 + assert time.perf_counter() - started < 10