From 5f94a6a3b0f8533204a2447751e75a48d14401e8 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 00:17:42 +0100 Subject: [PATCH 01/27] refactor(zarr-metadata): type v3 node documents by their TypedDict before reading them in a scope The v3 array and group readers now read a document in two steps. First `typed_document` checks each member against its annotation in the node's TypedDict, refining it once; then the semantic layer resolves each declaration in the scope and checks members against each other (fill value against data type, grid against shape, the codec pipeline, dimension names against shape). The hand-written checks that restated the annotations (`check_literal`, `dimension_lengths`, `attributes_of`, the inline `dimension_names` checks, `members_past_the_levels`) are gone from the v3 readers. `attributes` and unclaimed extra fields are annotated `UserJSONValue`, so the annotation decides where a non-finite number may be. Problems are now located at the bad entry (`("shape", 1)` rather than `("shape",)`), and reported in document order. Assisted-by: ClaudeCode:claude-opus-5-5 --- .../src/zarr_metadata/_typed_json.py | 19 +- .../zarr_metadata/definition/_definition.py | 208 ++++++++++++++++- .../src/zarr_metadata/model/_array_v3.py | 210 +++++------------- .../src/zarr_metadata/model/_group_v3.py | 51 ++--- .../src/zarr_metadata/v3/_common.py | 8 +- .../src/zarr_metadata/v3/array.py | 6 +- .../src/zarr_metadata/v3/group.py | 6 +- .../zarr-metadata/tests/model/test_array.py | 59 +++-- .../zarr-metadata/tests/model/test_group.py | 2 +- .../zarr-metadata/tests/model/test_pair.py | 4 +- .../tests/model/test_pydantic_module.py | 6 +- .../zarr-metadata/tests/test_typed_json.py | 2 +- .../tests/v3/test_grid_shapes.py | 2 +- 13 files changed, 362 insertions(+), 221 deletions(-) diff --git a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py index b774ddd586..abfd520d9a 100644 --- a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py @@ -530,6 +530,11 @@ def _holds(annotation: object, alias: object, seen: frozenset[object]) -> bool: return any(_holds(argument, alias, seen) for argument in get_args(inner)) +def holds(annotation: object, alias: object) -> bool: + """Whether `alias` occurs in `annotation`, at any depth of its type arguments, following any aliases in it. A TypedDict's members are not looked inside.""" + return _holds(annotation, alias, frozenset()) + + def shape_of(annotation: object) -> str | None: """The top-level JSON shape an annotation allows, used to choose a union branch. @@ -622,7 +627,19 @@ def parse(value: object, loc: Loc) -> Parsed: _BOOLEAN: Final = _scalar("a boolean", lambda value: isinstance(value, bool)) _STRING: Final = _scalar("a string", lambda value: isinstance(value, str)) _NULL: Final = _scalar("null", lambda value: value is None) -_JSON: Final = _scalar("a JSON value", is_json) + + +def _json(value: object, loc: Loc) -> Parsed: + """A member annotated `JSONValue`: JSON as RFC 8259 defines it. A value refined as user data may hold a number that is not finite, which is reported where it sits, as `refine_json` reports it.""" + if is_json(value): + return value, () + _, found = refine_json(value, loc) + if len(found) != 0: + return value, found + return value, problem(loc, f"expected a JSON value, got {shown(value)}") + + +_JSON: Final[Parser] = _json _USER_JSON: Final = _scalar("a JSON value", lambda value: is_canonical_json(value, finite=False)) diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index f59fea98a4..c5361102f3 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -60,7 +60,12 @@ from typing_extensions import TypeAliasType, TypeVar, is_typeddict -from zarr_metadata._common import EmptyConfiguration, JSONValue, ZarrV3NamedConfigJSON +from zarr_metadata._common import ( + EmptyConfiguration, + JSONValue, + UserJSONValue, + ZarrV3NamedConfigJSON, +) from zarr_metadata._json import ( Problems, ValidationProblem, @@ -73,13 +78,16 @@ refine_user_data, said, shown, + shown_key, with_input, + within, ) from zarr_metadata._sentinel import UNSET from zarr_metadata._typed_json import ( Loc, Parsed, Parser, + holds, is_alias, parser, problem, @@ -882,6 +890,200 @@ def _configuration_checked( return cast("T", _put_back(typed, _envelope_keys_only, nested)), problems +@dataclass(frozen=True, slots=True) +class FoundDeclaration: + """A declaration that `typed_document` found in a document: where the document holds it, the kind it is read as, and its JSON as written.""" + + loc: Loc + """The location of the declaration in the document.""" + kind: type[Definition[Any]] + """The kind the member's annotation reads the declaration as.""" + json: JSONValue + """The declaration as written, refined.""" + alias: TypeAliasType + """The declaration alias of the member that holds it, which may admit only some definitions of the kind.""" + finite: bool + """Whether the declaration was refined as JSON, so every number in it is finite. A declaration with a number that is not finite was refined as user data, and is refined again by its kind when a scope reads it.""" + + +@dataclass(frozen=True, slots=True) +class TypedDocument: + """A document's members as its TypedDict types them, before any scope reads its declarations.""" + + members: dict[str, JSONValue] + """Each member with no problem, by key, in the document's order: refined, then parsed as its annotation says, with each declaration it holds as written.""" + declarations: tuple[FoundDeclaration, ...] + """Each declaration the members hold, in the document's order, located in the document.""" + problems: Problems + """Every reason a member is not what its annotation says, located in the document.""" + + +@dataclass(frozen=True, slots=True) +class _Member: + """How `typed_document` reads one member of a document: whether the member is user data, the parser its annotation compiles to, and whether it holds declarations.""" + + user: bool + """Whether the annotation holds user data (`UserJSONValue`). Such a member is refined as user data, so a number that is not finite reaches the parser, which decides where it may be. Any other member is refined as JSON.""" + parse: Parser + nests: bool + """Whether the annotation holds a declaration alias, so the parsed member is searched for the declarations it holds. Such a member that is not JSON only for a number that is not finite is refined as user data instead, so its declarations are still read, and each is refused for such a number where it sits.""" + + +@dataclass(frozen=True, slots=True) +class _MemberParsers: + """How `typed_document` reads each member a document's TypedDict declares, and any other member.""" + + members: Mapping[str, _Member] + required: frozenset[str] + other: _Member | None + """How a member the TypedDict does not declare is read; None when it is closed, so such a member is an unknown key.""" + + +def _passed_on(value: object, loc: Loc) -> Parsed: + """A value the refining already checked, passed on as it is.""" + return value, () + + +class _MemberLeaf: + """The leaf `typed_document` compiles a member's parser with: a value the refining already checked (one of `passed`) is passed on, and each declaration is passed on to be read in a scope. It records whether it met a declaration alias.""" + + def __init__(self, passed: tuple[object, ...]) -> None: + self.passed = passed + self.nests = False + + def __call__(self, annotation: object) -> Parser | None: + if any(annotation is each for each in self.passed): + return _passed_on + found = _declaration(annotation) + if found is not None: + self.nests = True + return found + + +def _member(annotation: object) -> _Member: + """How `typed_document` reads a member annotated `annotation`. + + A value the refining already checked is passed on: user data, and a + JSON value in a member that is not user data and holds no declaration, + which is always refined as JSON. In any other member, a JSON value is + checked for numbers that are not finite. + """ + leaf = _MemberLeaf((UserJSONValue, JSONValue)) + parse = parser(annotation, leaf) + user = holds(annotation, UserJSONValue) + if not leaf.nests and not user: + return _Member(user=False, parse=parse, nests=False) + leaf = _MemberLeaf((UserJSONValue,)) + return _Member(user=user, parse=parser(annotation, leaf), nests=leaf.nests) + + +def _refined_member( + member: _Member, value: object, loc: Loc +) -> tuple[JSONValue | None, Problems, bool]: + """`value`, a member read as `member` says, refined: the value, every reason it is not JSON, and whether it was refined as JSON.""" + if member.user: + refined, found = refine_user_data(value, loc) + return refined, found, False + refined, found = refine_json(value, loc) + if len(found) == 0 or not member.nests: + return refined, found, True + refined, found = refine_user_data(value, loc) + return refined, found, False + + +@functools.cache +def _refines_as_json(kind: type[Definition[Any]]) -> bool: + """Whether `kind` refines its declarations as JSON, as `Definition._refined` does, rather than its own way.""" + return not any( + "_refined" in vars(base) for base in kind.__mro__[: kind.__mro__.index(Definition)] + ) + + +@functools.cache +def _member_parsers(shape: type) -> _MemberParsers: + """How `typed_document` reads each member of `shape`, a document's TypedDict, compiled once.""" + keys = typeddict_keys(shape) + other: _Member | None = None + if not keys.closed: + other = _member(UserJSONValue if keys.open else keys.extra_items) + return _MemberParsers( + MappingProxyType( + {key: _member(annotation) for key, (annotation, _) in keys.members.items()} + ), + keys.required, + other, + ) + + +def typed_document(doc: Mapping[object, object], shape: type, at: Loc = ()) -> TypedDocument: + """Type `doc`, a document at `at`, as `shape`, its TypedDict: the first step of reading a document, before any scope reads its declarations. + + Each member is checked on its own, so a problem in one does not hide a + problem in another. A member is refined once, from the root of the + input, so nesting depth counts from there, and then parsed as its + annotation says. The annotation decides where a number that is not + finite may be: in a value annotated `UserJSONValue` (a node's + attributes), and nowhere else. A member annotated with a declaration + alias holds a declaration, which is passed on as written for a scope + to read: its envelope and its numbers are checked there, by the kind + the alias names. A required member `doc` lacks, a key that is not a + string, and a key a closed TypedDict does not declare are problems. + """ + parsers = _member_parsers(shape) + problems: list[ValidationProblem] = [ + ValidationProblem((key,), "missing required key", "missing_key") + for key in sorted(parsers.required - doc.keys()) + ] + members: dict[str, JSONValue] = {} + found_declarations: list[FoundDeclaration] = [] + for key, value in doc.items(): + if not isinstance(key, str): + message = f"non-string top-level key {shown_key(key)}" + problems.append(ValidationProblem((), message, "invalid_type")) + continue + member = parsers.members.get(key, parsers.other) + if member is None: + problems.append(ValidationProblem((key,), f"unexpected key {key!r}", "unknown_key")) + continue + refined, found, finite = _refined_member(member, value, (*at, key)) + if len(found) != 0: + problems.extend(within(found, at)) + continue + typed, found = member.parse(refined, (key,)) + if len(found) != 0: + problems.extend(found) + continue + nested: list[_NestedDeclaration] = [] + if member.nests: + _collect(typed, nested) + members[key] = cast("JSONValue", _put_back(typed, _as_written, nested)) + found_declarations.extend( + FoundDeclaration(each.loc, each.kind, each.json, each.alias, finite) for each in nested + ) + return TypedDocument(members, tuple(found_declarations), tuple(problems)) + + +def read_found( + declaration: FoundDeclaration, context: Context, at: Loc = () +) -> tuple[ResolvedDeclaration[Any], Problems]: + """Read `declaration`, which `typed_document` found in a document at `at`, in `context`, as `resolve` reads it, and check that the member's alias admits the definition that read it. The problems are located in the document. + + A declaration `typed_document` refined as JSON is read without being + refined again, when its kind refines declarations as JSON. Any other is + refined again by its kind, so a number that is not finite refuses the + declaration, where it sits. + """ + loc = (*at, *declaration.loc) + if declaration.finite and _refines_as_json(declaration.kind): + resolved, found = resolve_refined( + declaration.json, declaration.json, (), declaration.kind, context, loc + ) + else: + resolved, found = resolve(declaration.json, declaration.kind, context, loc) + placed = _NestedDeclaration(loc, declaration.kind, declaration.json, declaration.alias) + return resolved, within((*found, *_sized(placed, resolved)), at) + + def named_configuration( value: object, ) -> tuple[str | None, Mapping[str, object] | None, Problems]: @@ -1943,10 +2145,12 @@ def _replaced(value: JSONValue, path: Loc, new: JSONValue) -> JSONValue: "C", "Context", "Definition", + "FoundDeclaration", "Nested", "Problems", "RefusedDeclaration", "ResolvedDeclaration", + "TypedDocument", "UnclaimedDeclaration", "WithFillValue", "as_kind", @@ -1971,12 +2175,14 @@ def _replaced(value: JSONValue, path: Loc, new: JSONValue) -> JSONValue: "named_configuration", "no_rules", "own_key", + "read_found", "read_only", "resolve", "resolve_refined", "respelled", "ruled", "spelled_canonically", + "typed_document", "unchanged", "with_problems", "written_json", diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py index 2ea2af7ccb..9f63a9edf8 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py @@ -6,7 +6,7 @@ from collections.abc import Mapping from dataclasses import dataclass from types import MappingProxyType -from typing import TYPE_CHECKING, Any, Final, Literal, cast, get_args, get_origin +from typing import TYPE_CHECKING, Any, Final, Literal, cast from typing_extensions import TypedDict, Unpack @@ -16,33 +16,28 @@ ValidationProblem, copied, frozen, - is_array, is_object, json_text, - nested_past_the_levels, not_an_object, - refine_json, - shown_key, with_input, within, ) from zarr_metadata._sentinel import UNSET -from zarr_metadata._typed_json import strip_annotation, typeddict_keys from zarr_metadata.definition._context import disagreements, scoped from zarr_metadata.definition._definition import ( AcceptedDeclaration, - Definition, ResolvedDeclaration, UnclaimedDeclaration, declaration_key, - declaration_kind, declarations_of, default_fill_value, fill_value_problems, held, + read_found, resolve, resolve_refined, spelled_canonically, + typed_document, ) from zarr_metadata.definition._scope import ScopeConflictError, claims_of from zarr_metadata.definition._scope import refines as refines_declaration @@ -51,14 +46,11 @@ from zarr_metadata.model._shared import ( Derived, StoreKey, - attributes_of, - check_literal, created, dimension_lengths, load_store_json, located_conflicts, member_changes, - missing_keys, reading_of, unclaimed_declarations_of, ) @@ -99,45 +91,6 @@ ) -def members_past_the_levels( - doc: Mapping[object, object], at: Loc -) -> dict[object, ValidationProblem]: - """Each member of `doc` (a document located at `at`) that is a container nested deeper than a reader walks, mapped to its problem, located in the document. - - A reader reports these members and does not walk into them. This - matches what `refine_json` would report for the whole document: a - document one level before the depth cap can hold scalars, and nothing - else. - """ - past: dict[object, ValidationProblem] = {} - for key, item in doc.items(): - if isinstance(key, str): - problem = nested_past_the_levels(item, (*at, key)) - if problem is not None: - (past[key],) = within((problem,), at) - return past - - -_MEMBERS_V3: Final = typeddict_keys(ZarrV3ArrayMetadataJSON).members - - -_EXTENSION_POINTS_V3: Final[tuple[tuple[str, type[Definition[Any]]], ...]] = tuple( - (key, kind) - for key, (annotation, _) in _MEMBERS_V3.items() - if (kind := declaration_kind(annotation)) is not None -) -"""The single extension points of a v3 array document, and the kind each is read as: each member that the TypedDict annotates with a declaration alias.""" - - -_EXTENSION_LISTS_V3: Final[tuple[tuple[str, type[Definition[Any]]], ...]] = tuple( - (key, kind) - for key, (annotation, _) in _MEMBERS_V3.items() - if get_origin(listed := strip_annotation(annotation)[0]) is tuple - and (kind := declaration_kind(get_args(listed)[0])) is not None -) -"""The lists of extension points of a v3 array document, and the kind each entry is read as: each member that the TypedDict annotates as a tuple of a declaration alias, whatever constraints the tuple carries.""" - - def no_extra_fields() -> Mapping[str, ResolvedDeclaration[Any]]: """The extra fields of a reading of a document that has none.""" return MappingProxyType({}) @@ -242,55 +195,46 @@ def read_array_v3( """ if not is_object(value): return ZarrV3ArrayMetadataReading(problems=not_an_object(value)), None - doc = value - problems: list[ValidationProblem] = list(missing_keys(_ARRAY_METADATA_REQUIRED_KEYS_V3, doc)) - past = members_past_the_levels(doc, at) - problems.extend(past.values()) - whole, doc = doc, {key: item for key, item in doc.items() if key not in past} - extra_fields, extra, found = read_extra_fields_v3(doc, ArrayExtraFieldDefinition, context, at) + # The document is read in two steps. First its TypedDict types each + # member, as its annotation says: the one statement of what a member + # holds. Then what the annotations cannot say is checked on the typed + # members: each declaration as the scope reads it, and each member + # against the others. + typed = typed_document(value, ZarrV3ArrayMetadataJSON, at) + problems: list[ValidationProblem] = list(typed.problems) + members = typed.members + extra_fields, extra, found = read_extra_fields_v3( + members, ArrayExtraFieldDefinition, context, at + ) problems.extend(found) - problems.extend(check_literal(doc, "zarr_format", 3)) - problems.extend(check_literal(doc, "node_type", "array")) - shape, shape_problems = dimension_lengths(doc, "shape") - problems.extend(shape_problems) - # Each extension point is read by `resolve`. It first checks the - # envelope. Every extension *point* must be understood, so a - # `must_understand` of `false` is refused at each one: ignoring a codec - # gives wrong bytes just as ignoring a data type gives wrong values. - # The spec names only the first three + # Each declaration is read by `resolve`. It first checks the envelope. + # Every extension *point* must be understood, so a `must_understand` of + # `false` is refused at each one: ignoring a codec gives wrong bytes + # just as ignoring a data type gives wrong values. The spec names only + # the first three # (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/core/index.rst#L1580-L1581), # which this reader treats as an oversight, not as permission. Then # `resolve` checks the configuration against the definition in # `context` that claims the name. `must_understand: false` keeps its # meaning where it has one: on an unknown top-level extension *field*, # which a reader really can skip. - # Each member is refined once, here, and the refined value is kept. - # The document the model holds is built from these values, so nothing - # is walked twice. - refined: dict[str, JSONValue] = { - **extra_fields, - "zarr_format": 3, - "node_type": "array", - "shape": shape, - } read: dict[str, ResolvedDeclaration[Any]] = {} - for key, kind in _EXTENSION_POINTS_V3: - if key in doc: - refined[key], found = refine_json(doc[key], (*at, key)) - read[key], found = resolve_refined( - doc[key], refined[key], found, kind, context, (*at, key) - ) - problems.extend(within(found, at)) - # The fill value must be JSON. It is checked against the data type the - # scope read, if any. If nothing in scope claims the data type, the - # fill value is not checked. - fill_value: JSONValue = None - if "fill_value" in doc: - fill_value, found = refine_json(doc["fill_value"], (*at, "fill_value")) - refined["fill_value"] = fill_value - problems.extend(within(found, at)) - if len(found) == 0 and "data_type" in read: - problems.extend(fill_value_problems(read["data_type"], fill_value, ("fill_value",))) + listed: dict[str, list[ResolvedDeclaration[Any]]] = {} + for declaration in typed.declarations: + resolved, found = read_found(declaration, context, at) + problems.extend(found) + key = cast("str", declaration.loc[0]) + if len(declaration.loc) == 1: + read[key] = resolved + else: + listed.setdefault(key, []).append(resolved) + shape = cast("tuple[int, ...] | None", members.get("shape")) + # A fill value that is JSON is checked against the data type the scope + # read, if any. If nothing in scope claims the data type, the fill + # value is not checked. + fill_value = members.get("fill_value") + if "fill_value" in members and "data_type" in read: + problems.extend(fill_value_problems(read["data_type"], fill_value, ("fill_value",))) # Once both are read, the chunk grid is checked against the shape. The # grid gives the chunk lengths the first codec receives: one entry for # each dimension of the shape, None where the length is unknown. @@ -298,24 +242,6 @@ def read_array_v3( if "chunk_grid" in read and shape is not None: lengths, found = chunk_grid_lengths(read["chunk_grid"], shape, ("chunk_grid",)) problems.extend(found) - listed: dict[str, list[ResolvedDeclaration[Any]]] = {} - for key, kind in _EXTENSION_LISTS_V3: - if key in doc: - entries = doc[key] - if not is_array(entries): - problems.append(ValidationProblem((key,), "expected an array", "invalid_type")) - else: - listed[key] = [] - items: list[JSONValue] = [] - for index, entry in enumerate(entries): - item, found = refine_json(entry, (*at, key, index)) - items.append(item) - resolved, found = resolve_refined( - entry, item, found, kind, context, (*at, key, index) - ) - listed[key].append(resolved) - problems.extend(within(found, at)) - refined[key] = tuple(items) # The codecs are read as a pipeline. The first codec receives the # grid's chunks, of the array's data type. The codecs are checked in # order, each against the chunk it receives. A valid pipeline holds @@ -325,34 +251,14 @@ def read_array_v3( if "codecs" in listed: pipeline, found = read_pipeline(listed["codecs"], chunk, ("codecs",)) problems.extend(found) - attributes: dict[str, JSONValue] | None = {} - if "attributes" in doc: - attributes, found = attributes_of(doc["attributes"], at) - refined["attributes"] = attributes - problems.extend(found) - if "dimension_names" in doc: - # Simple typed sequences (dimension_names, shape, chunks) report a single - # field-level loc, not per-bad-item locs; per-index locs are reserved for - # the declaration lists (codecs, storage_transformers). - names = doc["dimension_names"] - if not is_array(names): - problems.append( - ValidationProblem(("dimension_names",), "expected an array", "invalid_type") - ) - elif not all(item is None or isinstance(item, str) for item in names): - problems.append( - ValidationProblem( - ("dimension_names",), "expected an array of strings or null", "invalid_type" - ) - ) - elif shape is not None and len(names) != len(shape): - problems.append( - ValidationProblem( - ("dimension_names",), - "expected one name per dimension of shape", - "invalid_value", - ) + # The names are checked against the shape: one name for each dimension. + names = cast("tuple[str | None, ...] | None", members.get("dimension_names")) + if names is not None and shape is not None and len(names) != len(shape): + problems.append( + ValidationProblem( + ("dimension_names",), "expected one name per dimension of shape", "invalid_value" ) + ) reading = ZarrV3ArrayMetadataReading( data_type=read.get("data_type", UNSET), chunk_grid=read.get("chunk_grid", UNSET), @@ -361,39 +267,34 @@ def read_array_v3( pipeline=pipeline, storage_transformers=tuple(listed.get("storage_transformers", ())), extra_fields=MappingProxyType(extra), - problems=with_input(problems, whole), + problems=with_input(problems, value), ) - if len(problems) != 0 or shape is None or attributes is None: + if len(problems) != 0 or shape is None: return reading, None - dimension_names: tuple[str | None, ...] | UNSET = UNSET - if "dimension_names" in doc: - # An array of strings and nulls, as checked above. Refine it, so - # each string is as JSON writes it. - dimension_names = cast("tuple[str | None, ...]", refine_json(doc["dimension_names"])[0]) - refined["dimension_names"] = dimension_names - members = ArrayMembersV3( + attributes = cast("dict[str, JSONValue]", members.get("attributes", {})) + return reading, ArrayMembersV3( shape=shape, fill_value=fill_value, - dimension_names=dimension_names, + dimension_names=UNSET if names is None else names, attributes=attributes, extra_fields=extra_fields, - document={key: refined[key] for key in cast("Mapping[str, object]", doc)}, + document=members, ) - return reading, members def read_extra_fields_v3( - doc: Mapping[object, object], + members: Mapping[str, JSONValue], kind: type[ExtraFieldDefinition[Any]], context: ZarrV3Context, at: Loc, ) -> tuple[ dict[str, JSONValue], dict[str, ResolvedDeclaration[Any]], tuple[ValidationProblem, ...] ]: - """Read each member of `doc` (a document at `at`) that is not one of the `spec_members` of `kind` as an extra field of `kind`. + """Read each of `members` (the typed members of a document at `at`, as `typed_document` returns them) that is not one of the `spec_members` of `kind` as an extra field of `kind`. Returns three values: each member that is JSON, refined; each member - as the scope read it, by key; and every problem, located in `doc`. A + as the scope read it, by key; and every problem, located in the + document. A member that a definition in `context` claims is read by that definition, and must be an object whose numbers are finite, unless the definition reads user data. Any other member is not read: it is an @@ -403,12 +304,7 @@ def read_extra_fields_v3( values: dict[str, JSONValue] = {} declarations: dict[str, ResolvedDeclaration[Any]] = {} problems: list[ValidationProblem] = [] - for key, value in doc.items(): - if not isinstance(key, str): - problems.append( - ValidationProblem((), f"non-string top-level key {shown_key(key)}", "invalid_type") - ) - continue + for key, value in members.items(): if key in kind.spec_members: continue member = {key: value} diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py index 9c5d9dc006..b1d2bdef3d 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py @@ -39,7 +39,12 @@ from zarr_metadata._json import prefixed as _prefix from zarr_metadata._sentinel import UNSET from zarr_metadata.definition._context import disagreements, scoped -from zarr_metadata.definition._definition import UnclaimedDeclaration, declarations_of, held +from zarr_metadata.definition._definition import ( + UnclaimedDeclaration, + declarations_of, + held, + typed_document, +) from zarr_metadata.definition._scope import ( Conflict, ScopeConflictError, @@ -54,7 +59,6 @@ ZarrV3ArrayMetadataReading, array_key_of, extra_fields_key, - members_past_the_levels, must_understand_subset, no_extra_fields, read_array_metadata_v3, @@ -66,7 +70,6 @@ from zarr_metadata.model._keyed import Keyed from zarr_metadata.model._shared import ( StoreKey, - attributes_of, check_literal, load_store_json, located_conflicts, @@ -949,36 +952,28 @@ def read_group_v3( """ if not is_object(value): return ZarrV3GroupMetadataReading(problems=not_an_object(value)), None - doc = value - found: list[ValidationProblem] = list(missing_keys(_GROUP_METADATA_REQUIRED_KEYS_V3, doc)) - past = members_past_the_levels(doc, at) - found.extend(past.values()) - whole, doc = doc, {key: item for key, item in doc.items() if key not in past} - extra_fields, extra, others = read_extra_fields_v3(doc, GroupExtraFieldDefinition, context, at) + # As for an array: the TypedDict types each member first, then each + # member the spec does not define is read as the scope reads it. + typed = typed_document(value, ZarrV3GroupMetadataJSON, at) + found: list[ValidationProblem] = list(typed.problems) + members = typed.members + extra_fields, extra, others = read_extra_fields_v3( + members, GroupExtraFieldDefinition, context, at + ) found.extend(others) - found.extend(check_literal(doc, "zarr_format", 3)) - found.extend(check_literal(doc, "node_type", "group")) - attributes: dict[str, JSONValue] | None = {} - if "attributes" in doc: - attributes, problems = attributes_of(doc["attributes"], at) - found.extend(problems) + attributes: dict[str, JSONValue] | None = ( + cast("dict[str, JSONValue]", members.get("attributes", {})) + if "attributes" in members or "attributes" not in value + else None + ) member = extra_fields.get(ZARR_V3_CONSOLIDATED_METADATA_KEY) consolidated: dict[str, JSONValue] | UNSET = member if isinstance(member, dict) else UNSET reading = ZarrV3GroupMetadataReading( - problems=with_input(found, whole), extra_fields=MappingProxyType(extra) + problems=with_input(found, value), extra_fields=MappingProxyType(extra) ) - document: dict[str, JSONValue] | None = None - if len(found) == 0 and attributes is not None: - # The document the model holds: each member as refined above, in - # the document's order, built from what was read instead of being - # refined again. - refined: dict[str, JSONValue] = { - **extra_fields, - "zarr_format": 3, - "node_type": "group", - "attributes": attributes, - } - document = {key: refined[key] for key in cast("Mapping[str, object]", doc)} + # The document the model holds is the typed members, in the document's + # order, built from what was read instead of being refined again. + document = members if len(found) == 0 else None return reading, GroupMembersV3(attributes, extra_fields, consolidated, document) diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_common.py b/packages/zarr-metadata/src/zarr_metadata/v3/_common.py index da8f4f511a..74bf40b11d 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_common.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_common.py @@ -13,7 +13,7 @@ from typing_extensions import TypeAliasType, TypeIs -from zarr_metadata._common import JSONValue, ZarrV3NamedConfigJSON +from zarr_metadata._common import UserJSONValue, ZarrV3NamedConfigJSON from zarr_metadata._hierarchy import NodeType ZarrV3NodeType = NodeType @@ -34,9 +34,13 @@ def is_zarr_v3_node_type(value: object) -> TypeIs[ZarrV3NodeType]: return value in ZARR_V3_NODE_TYPE -ZarrV3ExtensionField: TypeAlias = JSONValue +ZarrV3ExtensionField: TypeAlias = UserJSONValue """The JSON value of an unknown top-level v3 metadata field. +A field nothing in scope claims is not interpreted, so, like attributes, +its numbers may also be `NaN`, `Infinity` or `-Infinity`. A definition that +claims the field decides what it holds. + An object carrying the literal member `must_understand: false` may be ignored. Every other JSON shape implicitly requires understanding; recognition itself belongs to the reader rather than this structural type. diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/array.py b/packages/zarr-metadata/src/zarr_metadata/v3/array.py index 1d13e60f64..b5c38d26df 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/array.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/array.py @@ -6,7 +6,7 @@ from annotated_types import Ge, MinLen from typing_extensions import TypedDict -from zarr_metadata._common import JSONValue +from zarr_metadata._common import JSONValue, UserJSONValue from zarr_metadata.v3._common import ( ZarrV3ChunkGridDeclaration, ZarrV3ChunkKeyEncodingDeclaration, @@ -54,8 +54,8 @@ class ZarrV3ArrayMetadataJSON(TypedDict, extra_items=ZarrV3ExtensionField): then zero or more bytes -> bytes codecs, so the list is never empty (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/core/index.rst#L974-L983). """ - attributes: NotRequired[Mapping[str, JSONValue]] - """User attributes: arbitrary JSON values by string key.""" + attributes: NotRequired[Mapping[str, UserJSONValue]] + """User attributes: arbitrary JSON values by string key, whose numbers may also be `NaN`, `Infinity` or `-Infinity`, as zarr-python writes them.""" storage_transformers: NotRequired[tuple[ZarrV3StorageTransformerDeclaration, ...]] """The storage transformers between the array and its store. diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/group.py b/packages/zarr-metadata/src/zarr_metadata/v3/group.py index 99c0431192..584564d1e8 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/group.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/group.py @@ -8,7 +8,7 @@ from typing_extensions import TypedDict -from zarr_metadata._common import JSONValue +from zarr_metadata._common import UserJSONValue from zarr_metadata.v3._common import ZarrV3ExtensionField @@ -25,8 +25,8 @@ class ZarrV3GroupMetadataJSON(TypedDict, extra_items=ZarrV3ExtensionField): """The Zarr format version, `3`.""" node_type: Literal["group"] """The kind of node the document describes, `"group"`.""" - attributes: NotRequired[Mapping[str, JSONValue]] - """User attributes: arbitrary JSON values by string key.""" + attributes: NotRequired[Mapping[str, UserJSONValue]] + """User attributes: arbitrary JSON values by string key, whose numbers may also be `NaN`, `Infinity` or `-Infinity`, as zarr-python writes them.""" ZarrV3GroupMetadataStoreKey = Literal["zarr.json"] diff --git a/packages/zarr-metadata/tests/model/test_array.py b/packages/zarr-metadata/tests/model/test_array.py index 2d2ae6cf27..debcc198be 100644 --- a/packages/zarr-metadata/tests/model/test_array.py +++ b/packages/zarr-metadata/tests/model/test_array.py @@ -1578,7 +1578,7 @@ def _set(key: str, value: object) -> Callable[[dict], object]: ), Expect( _mutate(_build_v3, _set("shape", [1, "x"])), - frozenset({("shape",)}), + frozenset({("shape", 1)}), id="shape-non-int-item", ), Expect( @@ -2099,20 +2099,22 @@ def test_error_replace_refuses_to_leave_out_a_member_a_document_holds() -> None: @pytest.mark.parametrize( - ("shape", "kind"), + ("shape", "loc", "kind"), [ - (5, "invalid_type"), - (None, "invalid_type"), - (("a",), "invalid_type"), - ((-1,), "invalid_value"), + (5, ("shape",), "invalid_type"), + (None, ("shape",), "invalid_type"), + (("a",), ("shape", 0), "invalid_type"), + ((-1,), ("shape", 0), "invalid_value"), ], ids=["a-number", "null", "not-integers", "negative"], ) -def test_error_create_default_reports_a_shape_it_cannot_read(shape: object, kind: str) -> None: +def test_error_create_default_reports_a_shape_it_cannot_read( + shape: object, loc: tuple[str | int, ...], kind: str +) -> None: """A shape that cannot be read is reported the way the read reports it, rather than as a failure to derive a grid from it.""" with pytest.raises(MetadataValidationError) as raised: ZarrV3ArrayMetadata.create_default(shape=shape) # pyright: ignore[reportArgumentType] - assert [(p.loc, p.kind) for p in raised.value.problems] == [(("shape",), kind)] + assert [(p.loc, p.kind) for p in raised.value.problems] == [(loc, kind)] @pytest.mark.parametrize( @@ -2336,7 +2338,7 @@ def test_shape_rejects_json_booleans() -> None: """JSON booleans are not integers: shape/chunks containing true/false are rejected (bool is an int subclass in Python, so isinstance alone passes).""" v3 = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"shape": (True, True)} - assert [p.loc for p in read_array_metadata_v3(v3).problems] == [("shape",)] + assert [p.loc for p in read_array_metadata_v3(v3).problems] == [("shape", 0), ("shape", 1)] v2 = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"chunks": (True,)} assert [p.loc for p in read_array_metadata_v2(v2).problems] == [("chunks",)] @@ -2345,7 +2347,7 @@ def test_shape_rejects_negative_dimensions() -> None: """Dimension lengths must be non-negative; a negative entry is invalid_value.""" v3 = dict(ZarrV3ArrayMetadata.create_default().to_json()) | {"shape": (-1,)} assert [(p.loc, p.kind) for p in read_array_metadata_v3(v3).problems] == [ - (("shape",), "invalid_value") + (("shape", 0), "invalid_value") ] v2 = dict(ZarrV2ArrayMetadata.create_default().to_json()) | {"chunks": (-5,)} assert [(p.loc, p.kind) for p in read_array_metadata_v2(v2).problems] == [ @@ -2702,10 +2704,21 @@ def test_a_problem_shows_an_integer_too_long_to_write_by_its_size( interpreter_writes_4300_digits: None, ) -> None: # `int` refuses to write more than 4,300 digits. The message gives the - # size instead of raising. + # size instead of raising. A v2 document's `zarr_format` is compared + # with the value as given; a v3 document's is refined first, which + # refuses the integer itself. + document = {**ZarrV2ArrayMetadata.create_default().to_json(), "zarr_format": 10**5000} + (problem,) = read_array_metadata_v2(document).problems + assert problem.message == f"expected 2, got an integer of {(10**5000).bit_length()} bits" document = {**ZarrV3ArrayMetadata.create_default().to_json(), "zarr_format": 10**5000} (problem,) = read_array_metadata_v3(document).problems - assert problem.message == f"expected 3, got an integer of {(10**5000).bit_length()} bits" + assert (problem.loc, problem.message) == ( + ("zarr_format",), + ( + f"an integer of {(10**5000).bit_length()} bits has more digits than JSON text " + "holds here, as sys.get_int_max_str_digits bounds it" + ), + ) (problem,) = resolve( {"name": "gzip", 10**5000: 1}, CodecDefinition, CORE_AND_EXTENSIONS_CONTEXT )[1] @@ -2715,10 +2728,10 @@ def test_a_problem_shows_an_integer_too_long_to_write_by_its_size( # When such an integer is inside a container (JSON or not) or a key, the # message says the interpreter will not write the value. for held in ([10**5000], [10**5000, object()]): - document = {**ZarrV3ArrayMetadata.create_default().to_json(), "zarr_format": held} - (problem,) = read_array_metadata_v3(document).problems + document = {**ZarrV2ArrayMetadata.create_default().to_json(), "zarr_format": held} + (problem,) = read_array_metadata_v2(document).problems assert ( - problem.message == "expected 3, got a value of type list the interpreter will not write" + problem.message == "expected 2, got a value of type list the interpreter will not write" ) (problem,) = resolve( {"name": "gzip", (10**5000,): 1}, CodecDefinition, CORE_AND_EXTENSIONS_CONTEXT @@ -2747,10 +2760,20 @@ def test_a_problem_shows_a_value_nested_too_deep_to_write_by_saying_so() -> None nested: list[object] = [] innermost.append(nested) innermost = nested - document = {**ZarrV3ArrayMetadata.create_default().to_json(), "zarr_format": deep} + document = {**ZarrV2ArrayMetadata.create_default().to_json(), "zarr_format": deep} # Only one problem: a value that the literal check refuses is not walked, # so the depth rule does not also check it. assert [ (problem.loc, problem.kind, problem.message) - for problem in read_array_metadata_v3(document).problems - ] == [(("zarr_format",), "invalid_type", "expected 3, got a value nested too deep to show")] + for problem in read_array_metadata_v2(document).problems + ] == [(("zarr_format",), "invalid_type", "expected 2, got a value nested too deep to show")] + # A v3 document's `zarr_format` is refined before its annotation checks + # it, so the depth rule reports the container past the cap. + (problem,) = read_array_metadata_v3( + {**ZarrV3ArrayMetadata.create_default().to_json(), "zarr_format": deep} + ).problems + assert (problem.loc[0], problem.kind, problem.message) == ( + "zarr_format", + "invalid_value", + f"nested deeper than the {JSON_DEPTH} levels a reader walks", + ) diff --git a/packages/zarr-metadata/tests/model/test_group.py b/packages/zarr-metadata/tests/model/test_group.py index a0956e93c0..e416f98a53 100644 --- a/packages/zarr-metadata/tests/model/test_group.py +++ b/packages/zarr-metadata/tests/model/test_group.py @@ -373,8 +373,8 @@ def nested(levels: int) -> dict[str, object]: (problem.loc[:4], len(problem.loc) + 1) for problem in read_consolidated_metadata_v3(member).problems ] == [ - (("metadata", "g", "acme_extra", "a"), JSON_DEPTH), (("metadata", "g", "attributes", "a"), JSON_DEPTH), + (("metadata", "g", "acme_extra", "a"), JSON_DEPTH), (("metadata", "h", "fill_value", "a"), JSON_DEPTH), (("metadata", "h", "codecs", 1), JSON_DEPTH), ] diff --git a/packages/zarr-metadata/tests/model/test_pair.py b/packages/zarr-metadata/tests/model/test_pair.py index 998a45e3f2..4f8abd3fd5 100644 --- a/packages/zarr-metadata/tests/model/test_pair.py +++ b/packages/zarr-metadata/tests/model/test_pair.py @@ -134,7 +134,7 @@ def test_error_a_document_with_a_problem_is_refused_at_construction() -> None: ZarrV3ArrayMetadata({**ARRAY, "fill_value": 300, "shape": [-1]}) assert sorted(problem.loc for problem in raised.value.problems) == [ ("fill_value",), - ("shape",), + ("shape", 0), ] @@ -565,7 +565,7 @@ def test_error_consolidated_metadata_with_a_problem_is_refused_at_the_documents_ member = {**MEMBER, "metadata": {"a": {**ARRAY, "shape": [-1]}}} with pytest.raises(MetadataValidationError) as raised: ZarrV3ConsolidatedMetadata(member) - assert [problem.loc for problem in raised.value.problems] == [("metadata", "a", "shape")] + assert [problem.loc for problem in raised.value.problems] == [("metadata", "a", "shape", 0)] reading = read_consolidated_metadata_v3(member) assert reading.problems == raised.value.problems assert reading.metadata is None diff --git a/packages/zarr-metadata/tests/model/test_pydantic_module.py b/packages/zarr-metadata/tests/model/test_pydantic_module.py index 3a80bd9739..9ada570aed 100644 --- a/packages/zarr-metadata/tests/model/test_pydantic_module.py +++ b/packages/zarr-metadata/tests/model/test_pydantic_module.py @@ -594,11 +594,11 @@ class Manifest(BaseModel): Manifest.model_validate({"metadata": doc}) errors = raised.value.errors() assert [(e["type"], e["loc"], e["input"]) for e in errors] == [ - ("invalid_type", ("metadata", "fill_value"), {"a": 1}), ("invalid_value", ("metadata", "codecs", 1, "configuration", "level"), 12), + ("invalid_type", ("metadata", "fill_value"), {"a": 1}), ] - assert errors[0]["msg"] == 'expected an integer, got {"a": 1}' - assert errors[1].get("ctx") == {"ge": 0, "le": 9} + assert errors[1]["msg"] == 'expected an integer, got {"a": 1}' + assert errors[0].get("ctx") == {"ge": 0, "le": 9} def test_a_message_holding_a_ctx_placeholder_is_reported_as_it_is() -> None: diff --git a/packages/zarr-metadata/tests/test_typed_json.py b/packages/zarr-metadata/tests/test_typed_json.py index 7684d07287..292abe8cd2 100644 --- a/packages/zarr-metadata/tests/test_typed_json.py +++ b/packages/zarr-metadata/tests/test_typed_json.py @@ -218,7 +218,7 @@ def test_a_value_of_the_shape_reads_as_itself( (tuple[int, ...], 5, (), "invalid_type"), (int | str, 2.5, (), "invalid_type"), (Mapping[str, int], {"k": "v"}, ("k",), "invalid_type"), - (JSONValue, {"k": object()}, (), "invalid_type"), + (JSONValue, {"k": object()}, ("k",), "invalid_type"), ( Blosc | Gzip, {"name": "gzip", "configuration": {"level": "x"}}, diff --git a/packages/zarr-metadata/tests/v3/test_grid_shapes.py b/packages/zarr-metadata/tests/v3/test_grid_shapes.py index d56dc4d366..9c8d593adb 100644 --- a/packages/zarr-metadata/tests/v3/test_grid_shapes.py +++ b/packages/zarr-metadata/tests/v3/test_grid_shapes.py @@ -146,7 +146,7 @@ def test_error_an_array_document_s_shape_that_is_not_read_leaves_its_grid_unjudg document["chunk_grid"] = _regular(4) document["shape"] = (4, -1) assert [(p.loc, p.kind) for p in read_array_metadata_v3(document).problems] == [ - (("shape",), "invalid_value") + (("shape", 1), "invalid_value") ] From 684fb3010145211fe0d49fc5620aa9523a9765a8 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 00:17:51 +0100 Subject: [PATCH 02/27] refactor(zarr-metadata): derive the v3 declaration envelope check from its TypedDict `envelope_problems` now parses a declaration as `str | ZarrV3NamedConfigJSON` and adds only what the annotation cannot say: the extension-name syntax, and `must_understand: false` where a reader must understand the declaration. Configuration values are passed on unread, so the envelope check still walks only the envelope. Assisted-by: ClaudeCode:claude-opus-5-5 --- .../src/zarr_metadata/definition/_envelope.py | 98 ++++++++----------- .../tests/v3/test_definitions.py | 2 +- 2 files changed, 43 insertions(+), 57 deletions(-) diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py b/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py index b47659068d..842fb83f6b 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py @@ -8,7 +8,9 @@ import re from typing import Final -from zarr_metadata._json import ValidationProblem, is_object, shown, shown_key +from zarr_metadata._common import JSONValue, ZarrV3NamedConfigJSON +from zarr_metadata._json import ValidationProblem, is_object, shown +from zarr_metadata._typed_json import Loc, Parsed, Parser, parser ENVELOPE_KEYS: frozenset[str] = frozenset({"name", "configuration", "must_understand"}) """The keys a declaration's envelope declares. Any other key is an unknown key.""" @@ -58,69 +60,53 @@ def name_problem(name: str, at: tuple[str | int, ...]) -> ValidationProblem | No return ValidationProblem(at, message, "invalid_value") +def _opaque(annotation: object) -> Parser | None: + """The leaf the envelope's checker uses: a value annotated `JSONValue` inside the envelope (a configuration member) is passed on unread. The definition that reads the configuration checks it, so the envelope check walks only the envelope.""" + if annotation is JSONValue: + return _passed_on + return None + + +def _passed_on(value: object, loc: Loc) -> Parsed: + return value, () + + +_ENVELOPE: Final[Parser] = parser(str | ZarrV3NamedConfigJSON, _opaque) +"""The checker of a v3 declaration's envelope, compiled from its annotation: a name, or an object with `name`, `configuration` and `must_understand`, and nothing else.""" + + def envelope_problems( value: object, *, allow_must_understand_false: bool ) -> tuple[ValidationProblem, ...]: """Every reason `value` is not a valid v3 declaration envelope. The contents of the configuration are not checked. - The envelope is the part around the configuration: a `name` that is a - valid extension name under the spec, a `configuration` that is an - object with string keys, a boolean `must_understand`, and no other - keys. `resolve` calls this on a declaration it has already narrowed to JSON, - so the configuration is walked only once. + The envelope's TypedDict, `ZarrV3NamedConfigJSON`, says what it holds: + a string `name`, an object `configuration`, a boolean + `must_understand`, and no other keys. What its annotation cannot say + is checked after it: the name must be a valid extension name under the + spec, and `must_understand` must not be `false` where a reader must + understand the declaration. `resolve` calls this on a declaration it + has already narrowed to JSON. """ - if isinstance(value, str): - bad = name_problem(value, ()) - return () if bad is None else (bad,) - if not is_object(value): - return ( - ValidationProblem( - (), - f"expected a declaration (string or extension object), got {shown(value)}", - "invalid_type", - ), - ) - declaration = value - problems: list[ValidationProblem] = [] - for key in declaration: - if not isinstance(key, str): - problems.append( - ValidationProblem( - (), f"non-string declaration key {shown_key(key)}", "invalid_type" - ) - ) - elif key not in ENVELOPE_KEYS: - problems.append(ValidationProblem((key,), f"unexpected key {key!r}", "unknown_key")) - if "name" not in declaration: - problems.append(ValidationProblem(("name",), "missing required key", "missing_key")) - elif not isinstance(declaration["name"], str): - problems.append(ValidationProblem(("name",), "expected a string name", "invalid_type")) - elif (bad := name_problem(declaration["name"], ("name",))) is not None: + _, found = _ENVELOPE(value, ()) + problems = list(found) + name, at = (value, ()) if isinstance(value, str) else (None, ("name",)) + if is_object(value): + name = value.get("name") + if isinstance(name, str) and (bad := name_problem(name, at)) is not None: problems.append(bad) - if "configuration" in declaration: - configuration = declaration["configuration"] - if not is_object(configuration): - problems.append( - ValidationProblem(("configuration",), "expected an object", "invalid_type") - ) - elif not all(isinstance(k, str) for k in configuration): - problems.append( - ValidationProblem(("configuration",), "expected string keys", "invalid_type") - ) - if "must_understand" in declaration: - must_understand = declaration["must_understand"] - if not isinstance(must_understand, bool): - problems.append( - ValidationProblem(("must_understand",), "expected a boolean", "invalid_type") - ) - elif not allow_must_understand_false and not must_understand: - problems.append( - ValidationProblem( - ("must_understand",), - "false is not supported at this extension point", - "invalid_value", - ) + if ( + is_object(value) + and not allow_must_understand_false + and value.get("must_understand") is False + ): + problems.append( + ValidationProblem( + ("must_understand",), + "false is not supported at this extension point", + "invalid_value", ) + ) return tuple(problems) diff --git a/packages/zarr-metadata/tests/v3/test_definitions.py b/packages/zarr-metadata/tests/v3/test_definitions.py index 359275a18f..07c398ac8d 100644 --- a/packages/zarr-metadata/tests/v3/test_definitions.py +++ b/packages/zarr-metadata/tests/v3/test_definitions.py @@ -1603,7 +1603,7 @@ def test_error_a_declaration_without_a_name_is_missing_one() -> None: resolved, problems = resolve({"configuration": {}}, CodecDefinition, CORE_CONTEXT) assert isinstance(resolved, RefusedDeclaration) assert [(p.loc, p.kind, p.message) for p in problems] == [ - (("name",), "missing_key", "missing required key") + (("name",), "missing_key", "missing required key 'name'") ] From 3ddee672abda9da654066d6abf46a125b8bff612 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 00:48:28 +0100 Subject: [PATCH 03/27] fix(zarr-metadata): report every problem the v3 type layer finds, and keep claimed extension fields The type layer from 5f94a6a3b refined a member whole before typing it, so a member holding a declaration that was not JSON lost its other problems, and a claimed extension field was refined by the type layer instead of by the definition that claims it. Now: - a member that holds a declaration is parsed as written, and each declaration is refined where it sits (`_FindingDeclaration`), so a declaration that is not JSON is refused by its kind without hiding problems elsewhere in the member; - other members are refined once, by `refine_json`, or by `refine_user_data` when annotated `UserJSONValue`, then typed; - a member the TypedDict does not declare is passed on as written to `read_extra_fields_v3`, which refines it by the claiming definition; - only members that can hold a declaration are walked again to collect and swap out declarations, so large attributes are not copied. Problem order is: the type layer (missing keys, non-string keys, member types), then extension fields, then declarations, then the cross-member checks (fill value, grid lengths, pipeline, dimension names). Removes the now unused `holds`, `_GROUP_METADATA_REQUIRED_KEYS_V3` and the hand-written v3 member constants. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../src/zarr_metadata/_typed_json.py | 5 - .../zarr_metadata/definition/_definition.py | 296 ++++++++++++------ .../src/zarr_metadata/model/_array_v3.py | 25 +- .../src/zarr_metadata/model/_group_v3.py | 23 +- 4 files changed, 215 insertions(+), 134 deletions(-) diff --git a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py index abfd520d9a..6f96be6d37 100644 --- a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py @@ -530,11 +530,6 @@ def _holds(annotation: object, alias: object, seen: frozenset[object]) -> bool: return any(_holds(argument, alias, seen) for argument in get_args(inner)) -def holds(annotation: object, alias: object) -> bool: - """Whether `alias` occurs in `annotation`, at any depth of its type arguments, following any aliases in it. A TypedDict's members are not looked inside.""" - return _holds(annotation, alias, frozenset()) - - def shape_of(annotation: object) -> str | None: """The top-level JSON shape an annotation allows, used to choose a union branch. diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index c5361102f3..5bba2ea532 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -71,9 +71,12 @@ ValidationProblem, copied, frozen, + is_array, + is_list_or_tuple, is_object, is_tuple, json_text, + nested_past_the_levels, refine_json, refine_user_data, said, @@ -87,7 +90,6 @@ Loc, Parsed, Parser, - holds, is_alias, parser, problem, @@ -892,142 +894,204 @@ def _configuration_checked( @dataclass(frozen=True, slots=True) class FoundDeclaration: - """A declaration that `typed_document` found in a document: where the document holds it, the kind it is read as, and its JSON as written.""" + """A declaration that `typed_document` found in a document: where the document holds it, the kind it is read as, and the declaration as written and as refined.""" loc: Loc """The location of the declaration in the document.""" kind: type[Definition[Any]] """The kind the member's annotation reads the declaration as.""" - json: JSONValue - """The declaration as written, refined.""" alias: TypeAliasType """The declaration alias of the member that holds it, which may admit only some definitions of the kind.""" - finite: bool - """Whether the declaration was refined as JSON, so every number in it is finite. A declaration with a number that is not finite was refined as user data, and is refined again by its kind when a scope reads it.""" + written: object + """The declaration as the document writes it.""" + json: JSONValue | None + """The declaration refined as JSON; None when it is not JSON.""" + problems: Problems + """Every reason the declaration is not JSON, located in the document.""" @dataclass(frozen=True, slots=True) class TypedDocument: - """A document's members as its TypedDict types them, before any scope reads its declarations.""" + """A document's members as its TypedDict types them, before any scope reads its declarations and extension fields.""" members: dict[str, JSONValue] - """Each member with no problem, by key, in the document's order: refined, then parsed as its annotation says, with each declaration it holds as written.""" + """Each member the TypedDict declares that has no problem of its type, by key, in the document's order, as refined and parsed; each declaration it holds is refined (None when it is not JSON, which `declarations` reports).""" declarations: tuple[FoundDeclaration, ...] - """Each declaration the members hold, in the document's order, located in the document.""" + """Each declaration the members hold, in the document's order.""" + extension_fields: dict[str, object] + """Each member the TypedDict does not declare, by key, as written, for the scope to read.""" problems: Problems """Every reason a member is not what its annotation says, located in the document.""" -@dataclass(frozen=True, slots=True) -class _Member: - """How `typed_document` reads one member of a document: whether the member is user data, the parser its annotation compiles to, and whether it holds declarations.""" +class _Refining: + """A leaf parser of a member parsed as written: it refines the value where the leaf sits, so nesting depth counts from the root of the input, and returns the refined value or the reasons it is not JSON.""" - user: bool - """Whether the annotation holds user data (`UserJSONValue`). Such a member is refined as user data, so a number that is not finite reaches the parser, which decides where it may be. Any other member is refined as JSON.""" - parse: Parser - nests: bool - """Whether the annotation holds a declaration alias, so the parsed member is searched for the declarations it holds. Such a member that is not JSON only for a number that is not finite is refined as user data instead, so its declarations are still read, and each is refused for such a number where it sits.""" + def __init__(self, refine: Callable[[object, Loc], tuple[JSONValue | None, Problems]]) -> None: + self.refine = refine + def __call__(self, value: object, loc: Loc) -> Parsed: + refined, found = self.refine(value, loc) + return (value if len(found) != 0 else refined), found -@dataclass(frozen=True, slots=True) -class _MemberParsers: - """How `typed_document` reads each member a document's TypedDict declares, and any other member.""" - members: Mapping[str, _Member] - required: frozenset[str] - other: _Member | None - """How a member the TypedDict does not declare is read; None when it is closed, so such a member is an unknown key.""" +class _FindingDeclaration: + """A leaf parser of a member parsed as written, for a member annotated with a declaration alias: it refines the declaration where it sits and passes it on, with any reason it is not JSON, for a scope to read. The declaration itself is never a problem of the member's type.""" + + def __init__(self, kind: type[Definition[Any]], alias: TypeAliasType) -> None: + self.kind = kind + self.alias = alias + + def __call__(self, value: object, loc: Loc) -> Parsed: + refined, found = refine_json(value, loc) + json = refined if len(found) == 0 else None + return FoundDeclaration(loc, self.kind, self.alias, value, json, found), () def _passed_on(value: object, loc: Loc) -> Parsed: - """A value the refining already checked, passed on as it is.""" + """A leaf parser for a value the refining of its member already checked: passed on as it is.""" return value, () class _MemberLeaf: - """The leaf `typed_document` compiles a member's parser with: a value the refining already checked (one of `passed`) is passed on, and each declaration is passed on to be read in a scope. It records whether it met a declaration alias.""" + """The leaf `typed_document` compiles a member's parser with, for one way of reading the member, recording whether the annotation holds user data or a declaration alias. + + `refined` reads a member refined as JSON: every JSON value is passed on. + `user` reads a member refined as user data: user data is passed on, + and a JSON value is checked for numbers that are not finite. `written` + reads a member as the document writes it: each JSON value, user data + and declaration is refined where it sits, so one that is not JSON does + not hide a problem elsewhere in the member. + """ - def __init__(self, passed: tuple[object, ...]) -> None: - self.passed = passed + def __init__(self, way: Literal["refined", "user", "written"]) -> None: + self.way = way + self.user = False self.nests = False def __call__(self, annotation: object) -> Parser | None: - if any(annotation is each for each in self.passed): - return _passed_on - found = _declaration(annotation) - if found is not None: - self.nests = True - return found + if annotation is UserJSONValue: + self.user = True + return _Refining(refine_user_data) if self.way == "written" else _passed_on + if annotation is JSONValue: + if self.way == "written": + return _Refining(refine_json) + return _passed_on if self.way == "refined" else None + kind = declaration_kind(annotation) + if kind is None or not is_alias(annotation): + return None + self.nests = True + return _FindingDeclaration(kind, annotation) + + +@dataclass(frozen=True, slots=True) +class _Member: + """How `typed_document` reads one member of a document: the parser its annotation compiles to, and how the member is refined before it, if at all.""" + + parse: Parser + refine: Callable[[object, Loc], tuple[JSONValue | None, Problems]] | None + """`refine_json` or `refine_user_data` for a member refined whole before it is parsed; None for a member that holds a declaration, which is parsed as written, each leaf refined where it sits.""" def _member(annotation: object) -> _Member: """How `typed_document` reads a member annotated `annotation`. - A value the refining already checked is passed on: user data, and a - JSON value in a member that is not user data and holds no declaration, - which is always refined as JSON. In any other member, a JSON value is - checked for numbers that are not finite. + A member that holds a declaration is parsed as written, so a + declaration that is not JSON is still passed on, and refused by the + scope, without hiding the other declarations of the member. A member + that holds user data is refined as user data, so the parser decides + where a number that is not finite may be. Any other member is refined + as JSON. """ - leaf = _MemberLeaf((UserJSONValue, JSONValue)) - parse = parser(annotation, leaf) - user = holds(annotation, UserJSONValue) - if not leaf.nests and not user: - return _Member(user=False, parse=parse, nests=False) - leaf = _MemberLeaf((UserJSONValue,)) - return _Member(user=user, parse=parser(annotation, leaf), nests=leaf.nests) - - -def _refined_member( - member: _Member, value: object, loc: Loc -) -> tuple[JSONValue | None, Problems, bool]: - """`value`, a member read as `member` says, refined: the value, every reason it is not JSON, and whether it was refined as JSON.""" - if member.user: - refined, found = refine_user_data(value, loc) - return refined, found, False - refined, found = refine_json(value, loc) - if len(found) == 0 or not member.nests: - return refined, found, True - refined, found = refine_user_data(value, loc) - return refined, found, False + probe = _MemberLeaf("refined") + parse = parser(annotation, probe) + if probe.nests: + return _Member(parser(annotation, _MemberLeaf("written")), refine=None) + if probe.user: + return _Member(parser(annotation, _MemberLeaf("user")), refine_user_data) + return _Member(parse, refine_json) -@functools.cache -def _refines_as_json(kind: type[Definition[Any]]) -> bool: - """Whether `kind` refines its declarations as JSON, as `Definition._refined` does, rather than its own way.""" - return not any( - "_refined" in vars(base) for base in kind.__mro__[: kind.__mro__.index(Definition)] - ) +@dataclass(frozen=True, slots=True) +class _MemberParsers: + """How `typed_document` reads each member a document's TypedDict declares.""" + + members: Mapping[str, _Member] + required: frozenset[str] + closed: bool + """Whether the TypedDict is closed, so a member it does not declare is an unknown key rather than an extension field.""" @functools.cache def _member_parsers(shape: type) -> _MemberParsers: """How `typed_document` reads each member of `shape`, a document's TypedDict, compiled once.""" keys = typeddict_keys(shape) - other: _Member | None = None - if not keys.closed: - other = _member(UserJSONValue if keys.open else keys.extra_items) return _MemberParsers( MappingProxyType( {key: _member(annotation) for key, (annotation, _) in keys.members.items()} ), keys.required, - other, + keys.closed, ) +def _found_in(value: object, found: list[FoundDeclaration]) -> None: + """Append to `found` each declaration the parser returned inside `value`, in order.""" + if isinstance(value, FoundDeclaration): + found.append(value) + elif is_tuple(value): + for entry in value: + _found_in(entry, found) + elif is_object(value): + for entry in value.values(): + _found_in(entry, found) + + +def _with_declarations_refined(value: object) -> object: + """`value`, a parsed member, with each declaration in it replaced by its refined JSON.""" + if isinstance(value, FoundDeclaration): + return value.json + if is_tuple(value): + return tuple(_with_declarations_refined(entry) for entry in value) + if is_object(value): + return {key: _with_declarations_refined(entry) for key, entry in value.items()} + return value + + +def _typed_member(member: _Member, value: object, at: Loc, key: str) -> tuple[object, Problems]: + """`value`, the member `key` of a document at `at`, read as `member` says: the parsed value and every problem, located in the document.""" + if member.refine is not None: + refined, found = member.refine(value, (*at, key)) + if len(found) != 0: + return None, within(found, at) + return member.parse(refined, (key,)) + # Parsed as written, from the root of the input. A container checks its + # own depth here; each leaf in it checks its own when it is refined. + past = nested_past_the_levels(value, (*at, key)) + if past is not None: + return None, within((past,), at) + if is_array(value) and not is_list_or_tuple(value): + value = tuple(value) + typed, found = member.parse(value, (*at, key)) + return typed, within(found, at) + + def typed_document(doc: Mapping[object, object], shape: type, at: Loc = ()) -> TypedDocument: - """Type `doc`, a document at `at`, as `shape`, its TypedDict: the first step of reading a document, before any scope reads its declarations. + """Type `doc`, a document at `at`, as `shape`, its TypedDict: the first step of reading a document, before any scope reads its declarations and extension fields. Each member is checked on its own, so a problem in one does not hide a - problem in another. A member is refined once, from the root of the - input, so nesting depth counts from there, and then parsed as its - annotation says. The annotation decides where a number that is not - finite may be: in a value annotated `UserJSONValue` (a node's - attributes), and nowhere else. A member annotated with a declaration - alias holds a declaration, which is passed on as written for a scope - to read: its envelope and its numbers are checked there, by the kind - the alias names. A required member `doc` lacks, a key that is not a - string, and a key a closed TypedDict does not declare are problems. + problem in another, and is refined once, from the root of the input, + so nesting depth counts from there. The annotation decides where a + number that is not finite may be: in a value annotated + `UserJSONValue` (a node's attributes), and nowhere else. A member + annotated with a declaration alias holds a declaration, which is + refined where it sits and passed on for a scope to read: its envelope + is checked there, by the kind the alias names, and one that is not + JSON is refused there. A member the TypedDict does not declare is an + extension field: what it holds is for the definition in scope that + claims its key, so it is passed on as written. A required member + `doc` lacks, a key that is not a string, and a key a closed TypedDict + does not declare are problems. """ parsers = _member_parsers(shape) problems: list[ValidationProblem] = [ @@ -1035,32 +1099,55 @@ def typed_document(doc: Mapping[object, object], shape: type, at: Loc = ()) -> T for key in sorted(parsers.required - doc.keys()) ] members: dict[str, JSONValue] = {} - found_declarations: list[FoundDeclaration] = [] + declarations: list[FoundDeclaration] = [] + extension_fields: dict[str, object] = {} for key, value in doc.items(): if not isinstance(key, str): message = f"non-string top-level key {shown_key(key)}" problems.append(ValidationProblem((), message, "invalid_type")) continue - member = parsers.members.get(key, parsers.other) + member = parsers.members.get(key) if member is None: - problems.append(ValidationProblem((key,), f"unexpected key {key!r}", "unknown_key")) + if parsers.closed: + problems.append(ValidationProblem((key,), f"unexpected key {key!r}", "unknown_key")) + else: + extension_fields[key] = value continue - refined, found, finite = _refined_member(member, value, (*at, key)) + typed, found = _typed_member(member, value, at, key) + problems.extend(found) if len(found) != 0: - problems.extend(within(found, at)) continue - typed, found = member.parse(refined, (key,)) - if len(found) != 0: - problems.extend(found) + if member.refine is not None: + members[key] = cast("JSONValue", typed) continue - nested: list[_NestedDeclaration] = [] - if member.nests: - _collect(typed, nested) - members[key] = cast("JSONValue", _put_back(typed, _as_written, nested)) - found_declarations.extend( - FoundDeclaration(each.loc, each.kind, each.json, each.alias, finite) for each in nested - ) - return TypedDocument(members, tuple(found_declarations), tuple(problems)) + found_here: list[FoundDeclaration] = [] + _found_in(typed, found_here) + members[key] = cast("JSONValue", _with_declarations_refined(typed)) + if len(at) == 0: + declarations.extend(found_here) + else: + # Built directly: `dataclasses.replace` costs more than the + # rest of the move, for every declaration in a listing. + declarations.extend( + FoundDeclaration( + each.loc[len(at) :], + each.kind, + each.alias, + each.written, + each.json, + within(each.problems, at), + ) + for each in found_here + ) + return TypedDocument(members, tuple(declarations), extension_fields, tuple(problems)) + + +@functools.cache +def _refines_as_json(kind: type[Definition[Any]]) -> bool: + """Whether `kind` refines its declarations as JSON, as `Definition._refined` does, rather than its own way.""" + return not any( + "_refined" in vars(base) for base in kind.__mro__[: kind.__mro__.index(Definition)] + ) def read_found( @@ -1068,18 +1155,23 @@ def read_found( ) -> tuple[ResolvedDeclaration[Any], Problems]: """Read `declaration`, which `typed_document` found in a document at `at`, in `context`, as `resolve` reads it, and check that the member's alias admits the definition that read it. The problems are located in the document. - A declaration `typed_document` refined as JSON is read without being - refined again, when its kind refines declarations as JSON. Any other is - refined again by its kind, so a number that is not finite refuses the - declaration, where it sits. + `typed_document` refined the declaration as JSON, which is how a kind + refines its declarations unless it says otherwise, so it is read + without being refined again. A kind that refines its declarations + otherwise refines this one its own way. """ loc = (*at, *declaration.loc) - if declaration.finite and _refines_as_json(declaration.kind): + if _refines_as_json(declaration.kind): resolved, found = resolve_refined( - declaration.json, declaration.json, (), declaration.kind, context, loc + declaration.written, + declaration.json, + _located(at, declaration.problems), + declaration.kind, + context, + loc, ) else: - resolved, found = resolve(declaration.json, declaration.kind, context, loc) + resolved, found = resolve(declaration.written, declaration.kind, context, loc) placed = _NestedDeclaration(loc, declaration.kind, declaration.json, declaration.alias) return resolved, within((*found, *_sized(placed, resolved)), at) diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py index 9f63a9edf8..34b290dac5 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py @@ -84,13 +84,6 @@ from zarr_metadata.v3.array import ZarrV3ArrayMetadataStoreKey -# The members a v3 array document must have. The members the spec defines -# are `ArrayExtraFieldDefinition.spec_members`; any other is an extra field. -_ARRAY_METADATA_REQUIRED_KEYS_V3: Final[frozenset[str]] = frozenset( - ZarrV3ArrayMetadataJSON.__required_keys__ -) - - def no_extra_fields() -> Mapping[str, ResolvedDeclaration[Any]]: """The extra fields of a reading of a document that has none.""" return MappingProxyType({}) @@ -204,7 +197,7 @@ def read_array_v3( problems: list[ValidationProblem] = list(typed.problems) members = typed.members extra_fields, extra, found = read_extra_fields_v3( - members, ArrayExtraFieldDefinition, context, at + typed.extension_fields, ArrayExtraFieldDefinition, context, at ) problems.extend(found) # Each declaration is read by `resolve`. It first checks the envelope. @@ -278,24 +271,26 @@ def read_array_v3( dimension_names=UNSET if names is None else names, attributes=attributes, extra_fields=extra_fields, - document=members, + document={ + key: members[key] if key in members else extra_fields[key] + for key in cast("Mapping[str, object]", value) + }, ) def read_extra_fields_v3( - members: Mapping[str, JSONValue], + fields: Mapping[str, object], kind: type[ExtraFieldDefinition[Any]], context: ZarrV3Context, at: Loc, ) -> tuple[ dict[str, JSONValue], dict[str, ResolvedDeclaration[Any]], tuple[ValidationProblem, ...] ]: - """Read each of `members` (the typed members of a document at `at`, as `typed_document` returns them) that is not one of the `spec_members` of `kind` as an extra field of `kind`. + """Read each of `fields`, the members of a document at `at` that its TypedDict does not declare, as written (`TypedDocument.extension_fields`), as an extra field of `kind`. Returns three values: each member that is JSON, refined; each member as the scope read it, by key; and every problem, located in the - document. A - member that a definition in `context` claims is read by that + document. A member that a definition in `context` claims is read by that definition, and must be an object whose numbers are finite, unless the definition reads user data. Any other member is not read: it is an `UnclaimedDeclaration`, and, like attributes, need only be JSON as Python's @@ -304,9 +299,7 @@ def read_extra_fields_v3( values: dict[str, JSONValue] = {} declarations: dict[str, ResolvedDeclaration[Any]] = {} problems: list[ValidationProblem] = [] - for key, value in members.items(): - if key in kind.spec_members: - continue + for key, value in fields.items(): member = {key: value} definition = context.claimant(kind, key) refined, found = kind._refined(member, (*at, key), definition) # pyright: ignore[reportPrivateUsage] diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py index b1d2bdef3d..6685c1cff3 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py @@ -107,13 +107,6 @@ from zarr_metadata.v3.group import ZarrV3GroupMetadataStoreKey -# The members a v3 group document must have. The members the spec defines -# are `GroupExtraFieldDefinition.spec_members`; any other is an extra field. -_GROUP_METADATA_REQUIRED_KEYS_V3: Final[frozenset[str]] = frozenset( - ZarrV3GroupMetadataJSON.__required_keys__ -) - - # Unlike the node aliases below, this one holds its union as a string: the # JSON TypedDicts are imported only for type checking, and the models are # defined later in this module. @@ -958,7 +951,7 @@ def read_group_v3( found: list[ValidationProblem] = list(typed.problems) members = typed.members extra_fields, extra, others = read_extra_fields_v3( - members, GroupExtraFieldDefinition, context, at + typed.extension_fields, GroupExtraFieldDefinition, context, at ) found.extend(others) attributes: dict[str, JSONValue] | None = ( @@ -971,9 +964,17 @@ def read_group_v3( reading = ZarrV3GroupMetadataReading( problems=with_input(found, value), extra_fields=MappingProxyType(extra) ) - # The document the model holds is the typed members, in the document's - # order, built from what was read instead of being refined again. - document = members if len(found) == 0 else None + # The document the model holds: each member as it was refined above, + # in the document's order, built from what was read instead of being + # refined again. + document = ( + { + key: members[key] if key in members else extra_fields[key] + for key in cast("Mapping[str, object]", value) + } + if len(found) == 0 + else None + ) return reading, GroupMembersV3(attributes, extra_fields, consolidated, document) From 8d76087c1fd264f25dd384899ca9fc1e2f2760a2 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 01:22:45 +0100 Subject: [PATCH 04/27] refactor(zarr-metadata): refuse at compile time the document members typed_document cannot read A member that holds a declaration is parsed as written, and only its declarations, JSON values and user data are refined where they sit; the member itself is made a tuple when it is another kind of array. Any other leaf (a scalar, a nested array) would have read a value that was never refined, so compiling such a member now raises `TypeError`. So does a declaration of a kind that refines its declarations its own way, which removes the unreachable `resolve` branch of `read_found`, and an open TypedDict whose other keys may hold anything but user data, since `typed_document` passes those on as written. `_collect` and `_putting_back` now take the declaration type, so the walk over a checker's `_NestedDeclaration`s and over `typed_document`'s `FoundDeclaration`s is one walk. Adds tests/model/test_typed_document.py: one test that every problem in a document is reported (a non-JSON codec beside a bad one, NaN and nesting past the levels in separate codecs, a claimed extension field), which fails before 3ddee672a, and one test for each compile-time error. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../zarr_metadata/definition/_definition.py | 118 +++++------ .../tests/model/test_typed_document.py | 186 ++++++++++++++++++ 2 files changed, 249 insertions(+), 55 deletions(-) create mode 100644 packages/zarr-metadata/tests/model/test_typed_document.py diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index 5bba2ea532..d7b638a333 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -93,6 +93,7 @@ is_alias, parser, problem, + strip_annotation, typeddict_keys, unread_in, ) @@ -113,6 +114,9 @@ T = TypeVar("T") +_Found = TypeVar("_Found") +"""A declaration as a checker returns it in a typed value: a `_NestedDeclaration` or a `FoundDeclaration`.""" + D = TypeVar("D", bound="Definition[Any]") @@ -742,20 +746,20 @@ def _typed( if not checker.nests: return typed, found, () nested: list[_NestedDeclaration] = [] - _collect(typed, nested) + _collect(typed, _NestedDeclaration, nested) return typed, found, tuple(nested) -def _collect(value: object, nested: list[_NestedDeclaration]) -> None: - """Append to `nested` each nested declaration that the checker returned inside `value`, in order.""" - if isinstance(value, _NestedDeclaration): - nested.append(value) +def _collect(value: object, kind: type[_Found], found: list[_Found]) -> None: + """Append to `found` each declaration of type `kind` (as a checker returns one: a `_NestedDeclaration` or a `FoundDeclaration`) inside `value`, in order.""" + if isinstance(value, kind): + found.append(value) elif is_tuple(value): for entry in value: - _collect(entry, nested) + _collect(entry, kind, found) elif is_object(value): for entry in value.values(): - _collect(entry, nested) + _collect(entry, kind, found) def _as_written(declaration: _NestedDeclaration) -> JSONValue: @@ -779,17 +783,19 @@ def _put_back( """Replace each of `nested` (the declarations the checker returned inside `value`) with the result of `put`. Return `value` unchanged when there are none.""" if len(nested) == 0: return value - return _putting_back(value, put) + return _putting_back(value, _NestedDeclaration, put) -def _putting_back(value: object, put: Callable[[_NestedDeclaration], JSONValue]) -> object: - """`_put_back` for a value that contains nested declarations: a recursive walk.""" - if isinstance(value, _NestedDeclaration): +def _putting_back( + value: object, kind: type[_Found], put: Callable[[_Found], JSONValue | None] +) -> object: + """`value` with each declaration of type `kind` inside it replaced by the result of `put`: a recursive walk.""" + if isinstance(value, kind): return put(value) if is_tuple(value): - return tuple(_putting_back(entry, put) for entry in value) + return tuple(_putting_back(entry, kind, put) for entry in value) if is_object(value): - return {key: _putting_back(entry, put) for key, entry in value.items()} + return {key: _putting_back(entry, kind, put) for key, entry in value.items()} return value @@ -962,14 +968,24 @@ class _MemberLeaf: reads a member as the document writes it: each JSON value, user data and declaration is refined where it sits, so one that is not JSON does not hide a problem elsewhere in the member. + + Only those leaves refine what they read, and only the member itself is + made a tuple when it is an array of another type, so a member read as + written may hold declarations, JSON values and user data, alone or in + one array. Anything else in it raises `TypeError` when the member is + compiled, rather than reading a value that was never refined. So does + a declaration of a kind that refines its declarations its own way, + since the leaf refines it as JSON. """ def __init__(self, way: Literal["refined", "user", "written"]) -> None: self.way = way self.user = False self.nests = False + self.top = True def __call__(self, annotation: object) -> Parser | None: + top, self.top = self.top, False if annotation is UserJSONValue: self.user = True return _Refining(refine_user_data) if self.way == "written" else _passed_on @@ -978,10 +994,16 @@ def __call__(self, annotation: object) -> Parser | None: return _Refining(refine_json) return _passed_on if self.way == "refined" else None kind = declaration_kind(annotation) - if kind is None or not is_alias(annotation): + if kind is not None and is_alias(annotation): + if not _refines_as_json(kind): + msg = f"{annotation!r} holds {kind.__name__} declarations, which are not refined as JSON, so a document member cannot hold them" + raise TypeError(msg) + self.nests = True + return _FindingDeclaration(kind, annotation) + if self.way != "written" or (top and get_origin(annotation) is tuple): return None - self.nests = True - return _FindingDeclaration(kind, annotation) + msg = f"a document member that holds a declaration may hold only declarations and JSON values, alone or in one array, not {annotation!r}" + raise TypeError(msg) @dataclass(frozen=True, slots=True) @@ -1024,8 +1046,16 @@ class _MemberParsers: @functools.cache def _member_parsers(shape: type) -> _MemberParsers: - """How `typed_document` reads each member of `shape`, a document's TypedDict, compiled once.""" + """How `typed_document` reads each member of `shape`, a document's TypedDict, compiled once. + + Raises `TypeError` for an open `shape` whose other keys may hold + anything but user data: `typed_document` passes those on as written, + for the definition that claims each one to read. + """ keys = typeddict_keys(shape) + if not keys.closed and strip_annotation(keys.extra_items)[0] is not UserJSONValue: + msg = f"{shape.__name__} must be closed, or have extra_items=UserJSONValue, to type a document" + raise TypeError(msg) return _MemberParsers( MappingProxyType( {key: _member(annotation) for key, (annotation, _) in keys.members.items()} @@ -1035,27 +1065,9 @@ def _member_parsers(shape: type) -> _MemberParsers: ) -def _found_in(value: object, found: list[FoundDeclaration]) -> None: - """Append to `found` each declaration the parser returned inside `value`, in order.""" - if isinstance(value, FoundDeclaration): - found.append(value) - elif is_tuple(value): - for entry in value: - _found_in(entry, found) - elif is_object(value): - for entry in value.values(): - _found_in(entry, found) - - -def _with_declarations_refined(value: object) -> object: - """`value`, a parsed member, with each declaration in it replaced by its refined JSON.""" - if isinstance(value, FoundDeclaration): - return value.json - if is_tuple(value): - return tuple(_with_declarations_refined(entry) for entry in value) - if is_object(value): - return {key: _with_declarations_refined(entry) for key, entry in value.items()} - return value +def _as_refined(declaration: FoundDeclaration) -> JSONValue | None: + """A declaration `typed_document` found, as refined: None when it is not JSON.""" + return declaration.json def _typed_member(member: _Member, value: object, at: Loc, key: str) -> tuple[object, Problems]: @@ -1121,8 +1133,8 @@ def typed_document(doc: Mapping[object, object], shape: type, at: Loc = ()) -> T members[key] = cast("JSONValue", typed) continue found_here: list[FoundDeclaration] = [] - _found_in(typed, found_here) - members[key] = cast("JSONValue", _with_declarations_refined(typed)) + _collect(typed, FoundDeclaration, found_here) + members[key] = cast("JSONValue", _putting_back(typed, FoundDeclaration, _as_refined)) if len(at) == 0: declarations.extend(found_here) else: @@ -1155,23 +1167,19 @@ def read_found( ) -> tuple[ResolvedDeclaration[Any], Problems]: """Read `declaration`, which `typed_document` found in a document at `at`, in `context`, as `resolve` reads it, and check that the member's alias admits the definition that read it. The problems are located in the document. - `typed_document` refined the declaration as JSON, which is how a kind - refines its declarations unless it says otherwise, so it is read - without being refined again. A kind that refines its declarations - otherwise refines this one its own way. + `typed_document` refined the declaration as JSON, which is how its + kind refines declarations (a member cannot hold a kind that refines + them otherwise), so it is read without being refined again. """ loc = (*at, *declaration.loc) - if _refines_as_json(declaration.kind): - resolved, found = resolve_refined( - declaration.written, - declaration.json, - _located(at, declaration.problems), - declaration.kind, - context, - loc, - ) - else: - resolved, found = resolve(declaration.written, declaration.kind, context, loc) + resolved, found = resolve_refined( + declaration.written, + declaration.json, + _located(at, declaration.problems), + declaration.kind, + context, + loc, + ) placed = _NestedDeclaration(loc, declaration.kind, declaration.json, declaration.alias) return resolved, within((*found, *_sized(placed, resolved)), at) diff --git a/packages/zarr-metadata/tests/model/test_typed_document.py b/packages/zarr-metadata/tests/model/test_typed_document.py new file mode 100644 index 0000000000..9f4b17d344 --- /dev/null +++ b/packages/zarr-metadata/tests/model/test_typed_document.py @@ -0,0 +1,186 @@ +"""Typing a v3 node document by its TypedDict before a scope reads it: `typed_document`.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, ClassVar + +import pytest +from typing_extensions import TypeAliasType, TypedDict + +from zarr_metadata._common import JSONValue, UserJSONValue +from zarr_metadata._json import JSON_DEPTH, Problems, refine_user_data +from zarr_metadata.definition import Definition +from zarr_metadata.definition._definition import typed_document +from zarr_metadata.model import ZarrV3ArrayMetadata, read_array_metadata_v3 +from zarr_metadata.v3._common import ZarrV3CodecDeclaration, ZarrV3DeclarationJSON +from zarr_metadata.v3.definition import CORE_CONTEXT, ArrayExtraFieldDefinition, ZarrV3Context + +if TYPE_CHECKING: + from zarr_metadata._typed_json import Loc + + +def _deep(levels: int) -> object: + value: object = 1 + for _ in range(levels): + value = [value] + return value + + +_PAST_THE_LEVELS = _deep(JSON_DEPTH + 10) + + +class _Note(TypedDict, closed=True): + note: UserJSONValue + must_understand: bool + + +_NOTE_CONTEXT = CORE_CONTEXT.union( + ZarrV3Context( + array_extra_fields=[ + ArrayExtraFieldDefinition(name="acme.note", configuration=_Note, finite=False) + ] + ) +) + + +def _array(**members: object) -> dict[str, object]: + doc = json.loads(json.dumps(ZarrV3ArrayMetadata.create_default(shape=(4,)).to_json())) + return {**doc, **members} + + +@pytest.mark.parametrize( + ("doc", "context", "expected"), + [ + # A declaration that is not JSON does not hide a problem in another + # declaration of the same member. + ( + _array( + codecs=[ + {"name": "bytes", "configuration": {1: 1}}, + {"name": "BAD"}, + ] + ), + CORE_CONTEXT, + { + (("codecs", 0, "configuration"), "invalid_type"), + (("codecs", 1, "name"), "invalid_value"), + }, + ), + ( + _array( + codecs=[ + {"name": "bytes", "configuration": {"endian": float("nan")}}, + {"name": "zstd", "configuration": {"level": _PAST_THE_LEVELS}}, + ] + ), + CORE_CONTEXT, + { + (("codecs", 0, "configuration", "endian"), "invalid_value"), + (("codecs", 1, "configuration", ...), "invalid_value"), + }, + ), + ( + _array( + codecs=[ + {"name": "bytes", "configuration": {"endian": "little"}}, + {"name": "gzip", "configuration": {"level": 99}}, + {"name": "zstd", "configuration": {"level": _PAST_THE_LEVELS}}, + ] + ), + CORE_CONTEXT, + { + (("codecs", 1, "configuration", "level"), "invalid_value"), + (("codecs", 2, "configuration", ...), "invalid_value"), + }, + ), + # A claimed extension field is refined by the definition that claims + # it: a number that is not finite is allowed where the definition + # allows one, and nesting past the levels is still a problem. + ( + _array( + **{"acme.note": {"note": [float("nan"), _PAST_THE_LEVELS], "must_understand": True}} + ), + _NOTE_CONTEXT, + {(("acme.note", "note", 1, ...), "invalid_value")}, + ), + ( + _array(**{"acme.note": {"note": [float("nan")], "must_understand": True}}), + _NOTE_CONTEXT, + set(), + ), + ], + ids=[ + "non-json-codec", + "nan-and-deep-codecs", + "bad-level-and-deep", + "claimed-deep", + "claimed-nan", + ], +) +def test_every_problem_in_a_document_is_reported( + doc: dict[str, object], context: ZarrV3Context, expected: set[tuple[Loc, str]] +) -> None: + reading = read_array_metadata_v3(doc, context=context) + # A problem past the levels is located at the container that holds + # too many levels, deep inside the member: it is compared by where it + # starts. + found = { + (problem.loc if len(problem.loc) <= 4 else (*problem.loc[:3], ...), problem.kind) + for problem in reading.problems + } + assert found == expected + if "acme.note" in doc: + assert "acme.note" in reading.extra_fields + + +class _PairDocument(TypedDict, closed=True): + pair: tuple[ZarrV3CodecDeclaration, float] + + +class _NestedDocument(TypedDict, closed=True): + nested: tuple[tuple[ZarrV3CodecDeclaration, ...], ...] + + +class _OpenDocument(TypedDict): + codec: ZarrV3CodecDeclaration + + +_OwnWayDeclaration = TypeAliasType("_OwnWayDeclaration", ZarrV3DeclarationJSON) + + +@dataclass(frozen=True, kw_only=True, slots=True, repr=False) +class _OwnWayDefinition(Definition[Any], kind=True, format=3): + label: ClassVar[str] = "own-way declaration" + declaration_aliases: ClassVar[tuple[TypeAliasType, ...]] = (_OwnWayDeclaration,) + + @classmethod + def _refined( + cls, data: object, loc: Loc, definition: Definition[Any] | None + ) -> tuple[JSONValue | None, Problems]: + return refine_user_data(data, loc) + + +class _OwnWayDocument(TypedDict, closed=True): + own: _OwnWayDeclaration + + +def test_error_a_member_holding_a_declaration_and_a_scalar_is_not_compiled() -> None: + with pytest.raises(TypeError, match="may hold only declarations and JSON values"): + typed_document({}, _PairDocument) + + +def test_error_a_member_holding_declarations_in_nested_arrays_is_not_compiled() -> None: + with pytest.raises(TypeError, match="may hold only declarations and JSON values"): + typed_document({}, _NestedDocument) + + +def test_error_a_member_holding_a_kind_that_refines_its_own_way_is_not_compiled() -> None: + with pytest.raises(TypeError, match="which are not refined as JSON"): + typed_document({}, _OwnWayDocument) + + +def test_error_a_document_whose_other_keys_are_not_user_data_is_not_compiled() -> None: + with pytest.raises(TypeError, match="must be closed, or have extra_items=UserJSONValue"): + typed_document({}, _OpenDocument) From 9553a2cc85374f0f0d1f9e5e40b1ca27a8ede0de Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 01:31:07 +0100 Subject: [PATCH 05/27] test(zarr-metadata): compare nesting-problem locations down to the configuration key Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/tests/model/test_typed_document.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/zarr-metadata/tests/model/test_typed_document.py b/packages/zarr-metadata/tests/model/test_typed_document.py index 9f4b17d344..75cb52a08d 100644 --- a/packages/zarr-metadata/tests/model/test_typed_document.py +++ b/packages/zarr-metadata/tests/model/test_typed_document.py @@ -78,7 +78,7 @@ def _array(**members: object) -> dict[str, object]: CORE_CONTEXT, { (("codecs", 0, "configuration", "endian"), "invalid_value"), - (("codecs", 1, "configuration", ...), "invalid_value"), + (("codecs", 1, "configuration", "level", ...), "invalid_value"), }, ), ( @@ -92,7 +92,7 @@ def _array(**members: object) -> dict[str, object]: CORE_CONTEXT, { (("codecs", 1, "configuration", "level"), "invalid_value"), - (("codecs", 2, "configuration", ...), "invalid_value"), + (("codecs", 2, "configuration", "level", ...), "invalid_value"), }, ), # A claimed extension field is refined by the definition that claims @@ -103,7 +103,7 @@ def _array(**members: object) -> dict[str, object]: **{"acme.note": {"note": [float("nan"), _PAST_THE_LEVELS], "must_understand": True}} ), _NOTE_CONTEXT, - {(("acme.note", "note", 1, ...), "invalid_value")}, + {(("acme.note", "note", 1, 0, ...), "invalid_value")}, ), ( _array(**{"acme.note": {"note": [float("nan")], "must_understand": True}}), @@ -127,7 +127,7 @@ def test_every_problem_in_a_document_is_reported( # too many levels, deep inside the member: it is compared by where it # starts. found = { - (problem.loc if len(problem.loc) <= 4 else (*problem.loc[:3], ...), problem.kind) + (problem.loc if len(problem.loc) <= 5 else (*problem.loc[:4], ...), problem.kind) for problem in reading.problems } assert found == expected From 32b45eb4633aff80638aeb7fe17ffce9c18d2b86 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 09:52:28 +0100 Subject: [PATCH 06/27] docs(zarr-metadata): add the changelog entry for typing v3 node documents first Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/changes/493.feature.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 packages/zarr-metadata/changes/493.feature.md diff --git a/packages/zarr-metadata/changes/493.feature.md b/packages/zarr-metadata/changes/493.feature.md new file mode 100644 index 0000000000..fa5f35e88c --- /dev/null +++ b/packages/zarr-metadata/changes/493.feature.md @@ -0,0 +1 @@ +Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is now located at the element, such as `('shape', 1)`, rather than at the member, and nesting inside `shape` is counted from the root of the input, also in a consolidated listing. The annotations now say where a number that is not finite may appear: `attributes` and unclaimed extension fields are typed `UserJSONValue`, and the generated JSON Schema gives the documents' other keys that type. Some problem messages, and the order problems are reported in, have changed. From e2ecccad3c60d22db4f9c02151cdeb625b81929e Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 10:24:56 +0100 Subject: [PATCH 07/27] refactor(zarr-metadata): refine values inside the annotation checker and type documents with it The checker in `_typed_json` assumed refined JSON, so reading a v3 node document needed a parallel member-by-member refine around it (the `_MemberLeaf` probe compile, `_Refining`, `_FindingDeclaration`, `FoundDeclaration`, `_Member`, `_MemberParsers`, and compile-time guards for the leaves that machinery could not refine). That duplicated the checker and `_NestedDeclaration`. Each parser now refines what it reads: a scalar or `Literal` reads a `StrEnum` or `IntEnum` member as its JSON, an array may be any sequence and a mapping any mapping, a number must be finite except under `UserJSONValue`, and a container must sit within `JSON_DEPTH` levels of the root, which `loc` locates it below. A value that is not JSON is reported where it sits; a container where a scalar is expected is reported once as the wrong type, as v2 documents already were. `typed_document` is now the document's TypedDict checker (`_checker`) plus the existing `_NestedDeclaration` walk, restricted to the members that can hold a declaration (`_declaring`) and typed cleanly. The declaration leaf refines each declaration where it sits and carries the declaration as written and every reason it is not JSON, which `read_found` hands to `resolve_refined`. `typed_json.check` no longer refines the whole value first, so it honors `UserJSONValue`. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../src/zarr_metadata/_typed_json.py | 102 ++++- .../zarr_metadata/definition/_definition.py | 408 +++++------------- .../src/zarr_metadata/model/_array_v3.py | 4 +- .../zarr-metadata/tests/model/test_array.py | 21 +- .../tests/model/test_pydantic_module.py | 2 +- .../tests/model/test_read_array_metadata.py | 3 +- .../tests/model/test_typed_document.py | 63 +-- .../zarr-metadata/tests/test_typed_json.py | 88 +++- 8 files changed, 291 insertions(+), 400 deletions(-) diff --git a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py index 6f96be6d37..2ddddd002d 100644 --- a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py @@ -73,16 +73,18 @@ from zarr_metadata._common import JSONValue, UserJSONValue from zarr_metadata._json import ( + JSON_DEPTH, ValidationProblem, choices, copied, - is_canonical_json, - is_json, + is_array, is_list_or_tuple, is_object, listed, + nested_past_the_levels, outside_of, refine_json, + refine_user_data, shown, with_input, ) @@ -582,7 +584,7 @@ def fixed_length(annotation: object) -> int | None: def _has_length(length: int | None, value: object) -> bool: """Whether `value` has `length` elements, when a branch is an array of a fixed length. Any value passes a branch without one.""" - return length is None or (is_list_or_tuple(value) and len(value) == length) + return length is None or (is_array(value) and len(value) == length) def has_shape(shape: str | None, value: object) -> bool: @@ -599,15 +601,53 @@ def has_shape(shape: str | None, value: object) -> bool: if shape == "null": return value is None if shape == "tuple": - return isinstance(value, (list, tuple)) + return is_array(value) return isinstance(value, Mapping) # "mapping" # --- the parsers --------------------------------------------------------- +# +# A parser refines what it reads as it checks it, so it takes a value as a +# document holds it, not only canonical JSON: a scalar comes back as the +# JSON value it stands for (a `StrEnum` member as its string), an array of +# any kind of sequence comes back as a tuple, and any mapping as a dict. A +# number must be finite, except in a value annotated `UserJSONValue`, and a +# container must sit within `JSON_DEPTH` levels of the root of the +# document, which `loc` locates it below. So a value that is not JSON is +# reported where it sits, as `refine_json` reports it, and does not hide a +# problem anywhere else in the document. + + +def _plain(value: object) -> bool: + """Whether `value` is a JSON scalar of a type `json.loads` builds, which needs no refining. Nearly every value is one, so this is checked first, by type alone.""" + cls = type(value) + if cls is str or cls is bool or value is None: + return True + if cls is float: + return math.isfinite(cast("float", value)) + return cls is int and cast("int", value).bit_length() <= 64 + + +def _container(value: object) -> bool: + """Whether `value` is a JSON container as Python represents one: a mapping or a sequence that is not text.""" + return is_object(value) or is_array(value) + + +def _too_deep(value: object, loc: Loc) -> tuple[ValidationProblem, ...]: + """The problem for `value`, a container at `loc`, if it sits deeper than `JSON_DEPTH` levels below the root of the document.""" + if len(loc) < JSON_DEPTH: + return () + past = nested_past_the_levels(value, loc) + return () if past is None else (past,) def _scalar(description: str, admits: Callable[[object], bool]) -> Parser: def parse(value: object, loc: Loc) -> Parsed: + if not _plain(value) and not _container(value): + refined, found = refine_json(value, loc) + if len(found) != 0: + return value, found + value = refined if admits(value): return value, () return value, problem(loc, f"expected {description}, got {shown(value)}") @@ -625,17 +665,19 @@ def parse(value: object, loc: Loc) -> Parsed: def _json(value: object, loc: Loc) -> Parsed: - """A member annotated `JSONValue`: JSON as RFC 8259 defines it. A value refined as user data may hold a number that is not finite, which is reported where it sits, as `refine_json` reports it.""" - if is_json(value): - return value, () - _, found = refine_json(value, loc) - if len(found) != 0: - return value, found - return value, problem(loc, f"expected a JSON value, got {shown(value)}") + """A member annotated `JSONValue`: JSON as RFC 8259 defines it, refined, or every reason it is not JSON, each where it sits.""" + refined, found = refine_json(value, loc) + return (value if len(found) != 0 else refined), found + + +def _user_json(value: object, loc: Loc) -> Parsed: + """A member annotated `UserJSONValue`: JSON in which a number need not be finite, refined, or every other reason it is not JSON.""" + refined, found = refine_user_data(value, loc) + return (value if len(found) != 0 else refined), found _JSON: Final[Parser] = _json -_USER_JSON: Final = _scalar("a JSON value", lambda value: is_canonical_json(value, finite=False)) +_USER_JSON: Final[Parser] = _user_json def one_of(allowed: tuple[object, ...]) -> Parser: @@ -649,6 +691,11 @@ def one_of(allowed: tuple[object, ...]) -> Parser: """ def parse(value: object, loc: Loc) -> Parsed: + if not _plain(value) and not _container(value): + refined, found = refine_json(value, loc) + if len(found) != 0: + return value, found + value = refined if not any(value == entry and type(value) is type(entry) for entry in allowed): return value, (outside_of(loc, value, allowed),) return value, () @@ -660,8 +707,11 @@ def sequence_of(element: Parser) -> Parser: """A member whose type is an array of one element type, parsed element by element.""" def parse(value: object, loc: Loc) -> Parsed: - if not is_list_or_tuple(value): + if not is_list_or_tuple(value) and not is_array(value): return value, problem(loc, f"expected an array, got {shown(value)}") + deep = _too_deep(value, loc) + if len(deep) != 0: + return value, deep entries = value parsed: list[object] = [] found: list[ValidationProblem] = [] @@ -678,8 +728,11 @@ def fixed_tuple(elements: Sequence[Parser], description: str) -> Parser: """A member whose type is an array of a fixed length, parsed position by position.""" def parse(value: object, loc: Loc) -> Parsed: - if not is_list_or_tuple(value): + if not is_list_or_tuple(value) and not is_array(value): return value, problem(loc, f"expected {description}, got {shown(value)}") + deep = _too_deep(value, loc) + if len(deep) != 0: + return value, deep entries = tuple(value) if len(entries) != len(elements): return entries, problem(loc, f"expected {description}, got {shown(entries)}") @@ -768,6 +821,9 @@ def _by_tag(branches: Sequence[Branch], tag: Tag, value: object, loc: Loc) -> Pa if not is_object(value) or key not in value: return value, problem((*loc, key), f"missing required key {key!r}", "missing_key") said = value[key] + if not _plain(said) and not _container(said): + refined, found = refine_json(said, (*loc, key)) + said = said if len(found) != 0 else refined index = picks.get((type(said), said)) if _hashable(said) else None if index is None: return value, (outside_of((*loc, key), said, tuple(entry for _, entry in picks)),) @@ -799,6 +855,9 @@ def object_of(members: Mapping[str, tuple[Parser, bool]], extra: Parser | None) def parse(value: object, loc: Loc) -> Parsed: if not is_object(value): return value, problem(loc, f"expected an object, got {shown(value)}") + deep = _too_deep(value, loc) + if len(deep) != 0: + return value, deep entries = value parsed: dict[str, object] = {} found: list[ValidationProblem] = [] @@ -836,6 +895,9 @@ def mapping_of(value: Parser) -> Parser: def parse(candidate: object, loc: Loc) -> Parsed: if not is_object(candidate): return candidate, problem(loc, f"expected an object, got {shown(candidate)}") + deep = _too_deep(candidate, loc) + if len(deep) != 0: + return candidate, deep entries = candidate parsed: dict[str, object] = {} found: list[ValidationProblem] = [] @@ -1514,9 +1576,10 @@ def check( ) -> tuple[T | None, tuple[ValidationProblem, ...]]: """Type-check `value` as `shape`, a TypedDict. Returns the typed value or None, and every problem. - This function first refines `value` to JSON (arrays as tuples, string - keys, finite floats), then checks it member by member. Each problem is - located under `loc`. The returned value holds only what `shape` allows. + The check refines `value` as it goes (arrays as tuples, string keys, + a number finite except where the annotation is `UserJSONValue`), so a + part that is not JSON is reported where it sits, beside the problems + of every other member. Each problem is located under `loc`. The returned value holds only what `shape` allows. A key that a closed TypedDict does not declare is reported as `unknown_key` and left out, and the value is still returned. Any other problem means the value is not returned (None). The nesting-depth limit @@ -1528,10 +1591,7 @@ def check( if not is_typeddict(shape): msg = f"{shape!r} is not a TypedDict" raise TypeError(msg) - refined, problems = refine_json(value, loc) - if len(problems) != 0: - return None, with_input(problems, value, loc) - typed, found = _checker(shape)(refined, loc) + typed, found = _checker(shape)(value, loc) readable = all(problem.kind == "unknown_key" for problem in found) return (cast("T", typed) if readable else None), with_input(found, value, loc) diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index d7b638a333..b74afe1153 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -63,7 +63,6 @@ from zarr_metadata._common import ( EmptyConfiguration, JSONValue, - UserJSONValue, ZarrV3NamedConfigJSON, ) from zarr_metadata._json import ( @@ -71,17 +70,13 @@ ValidationProblem, copied, frozen, - is_array, - is_list_or_tuple, is_object, is_tuple, json_text, - nested_past_the_levels, refine_json, refine_user_data, said, shown, - shown_key, with_input, within, ) @@ -93,7 +88,6 @@ is_alias, parser, problem, - strip_annotation, typeddict_keys, unread_in, ) @@ -114,9 +108,6 @@ T = TypeVar("T") -_Found = TypeVar("_Found") -"""A declaration as a checker returns it in a typed value: a `_NestedDeclaration` or a `FoundDeclaration`.""" - D = TypeVar("D", bound="Definition[Any]") @@ -600,7 +591,7 @@ def claimant(self, kind: type[D], name: str) -> D | None: @dataclass(frozen=True, slots=True) class _NestedDeclaration: - """A declaration that the check found inside a configuration: its location, its kind, and its JSON. + """A declaration that the check found in a configuration or a document: its location, its kind, and its JSON. The checker returns this in place of the JSON wherever a declaration alias appears. `_checked` collects each one and puts its JSON back. It is @@ -611,29 +602,33 @@ class _NestedDeclaration: loc: Loc kind: type[Definition[Any]] json: JSONValue + """The declaration refined as JSON; None when it is not JSON.""" alias: TypeAliasType """Whether the member that holds it accepts only codecs of static size.""" + written: object + """The declaration as written.""" + problems: Problems + """Every reason the declaration is not JSON, located in the input.""" -def _declaration(annotation: object) -> Parser | None: - """The one checker shape that this module defines: a member that holds a declaration. +class _DeclarationParser: + """The parser of a member that holds a declaration: it refines the declaration where it sits and passes it on, with every reason it is not JSON. The declaration itself is never a problem of the member's type: whoever reads it (`check` without a scope, `resolve` with one) checks the envelope and maps the name to a definition, and refuses one that is not JSON.""" - The value is checked only as a bare name or an object, and passed on. - Whoever reads the declaration (`check` without a scope, `resolve` with one) - checks the envelope and maps the name to a definition. - """ + def __init__(self, kind: type[Definition[Any]], alias: TypeAliasType) -> None: + self.kind = kind + self.alias = alias + + def __call__(self, value: object, loc: Loc) -> Parsed: + refined, found = refine_json(value, loc) + return _NestedDeclaration(loc, self.kind, refined, self.alias, value, found), () + + +def _declaration(annotation: object) -> Parser | None: + """The one checker shape that this module defines: a member that holds a declaration.""" kind = declaration_kind(annotation) if kind is None or not is_alias(annotation): return None - alias = annotation - - def parse(value: object, loc: Loc) -> Parsed: - # The value is refined JSON, which the checker types only as - # `object`. If it is not a declaration at all, the kind's envelope check - # reports that. - return _NestedDeclaration(loc, kind, cast("JSONValue", value), alias), () - - return parse + return _DeclarationParser(kind, annotation) def _vetting(annotation: object) -> Parser | None: @@ -715,18 +710,36 @@ class _Checker: nests: bool +class _Meeting: + """The leaf of a checker: `_declaration`, recording whether the annotation it compiles holds a declaration anywhere.""" + + def __init__(self) -> None: + self.met = False + + def __call__(self, annotation: object) -> Parser | None: + found = _declaration(annotation) + self.met = self.met or found is not None + return found + + @functools.cache def _checker(shape: type) -> _Checker: """The checker for a TypedDict, compiled once. Raises `TypeError` naming any part that no checker reads.""" - met: list[object] = [] + meeting = _Meeting() + parse = parser(shape, meeting) + return _Checker(parse, meeting.met) - def leaf(annotation: object) -> Parser | None: - found = _declaration(annotation) - if found is not None: - met.append(annotation) - return found - return _Checker(parser(shape, leaf), len(met) != 0) +@functools.cache +def _declaring(shape: type) -> frozenset[str]: + """The members of `shape`, a TypedDict, whose values may hold a declaration, so a search for declarations walks only these.""" + held: set[str] = set() + for key, (annotation, _) in typeddict_keys(shape).members.items(): + meeting = _Meeting() + parser(annotation, meeting) + if meeting.met: + held.add(key) + return frozenset(held) def _checked( @@ -746,20 +759,20 @@ def _typed( if not checker.nests: return typed, found, () nested: list[_NestedDeclaration] = [] - _collect(typed, _NestedDeclaration, nested) + _collect(typed, nested) return typed, found, tuple(nested) -def _collect(value: object, kind: type[_Found], found: list[_Found]) -> None: - """Append to `found` each declaration of type `kind` (as a checker returns one: a `_NestedDeclaration` or a `FoundDeclaration`) inside `value`, in order.""" - if isinstance(value, kind): - found.append(value) +def _collect(value: object, nested: list[_NestedDeclaration]) -> None: + """Append to `nested` each nested declaration that the checker returned inside `value`, in order.""" + if isinstance(value, _NestedDeclaration): + nested.append(value) elif is_tuple(value): for entry in value: - _collect(entry, kind, found) + _collect(entry, nested) elif is_object(value): for entry in value.values(): - _collect(entry, kind, found) + _collect(entry, nested) def _as_written(declaration: _NestedDeclaration) -> JSONValue: @@ -783,19 +796,17 @@ def _put_back( """Replace each of `nested` (the declarations the checker returned inside `value`) with the result of `put`. Return `value` unchanged when there are none.""" if len(nested) == 0: return value - return _putting_back(value, _NestedDeclaration, put) + return _putting_back(value, put) -def _putting_back( - value: object, kind: type[_Found], put: Callable[[_Found], JSONValue | None] -) -> object: - """`value` with each declaration of type `kind` inside it replaced by the result of `put`: a recursive walk.""" - if isinstance(value, kind): +def _putting_back(value: object, put: Callable[[_NestedDeclaration], JSONValue]) -> object: + """`_put_back` for a value that contains nested declarations: a recursive walk.""" + if isinstance(value, _NestedDeclaration): return put(value) if is_tuple(value): - return tuple(_putting_back(entry, kind, put) for entry in value) + return tuple(_putting_back(entry, put) for entry in value) if is_object(value): - return {key: _putting_back(entry, kind, put) for key, entry in value.items()} + return {key: _putting_back(entry, put) for key, entry in value.items()} return value @@ -898,290 +909,88 @@ def _configuration_checked( return cast("T", _put_back(typed, _envelope_keys_only, nested)), problems -@dataclass(frozen=True, slots=True) -class FoundDeclaration: - """A declaration that `typed_document` found in a document: where the document holds it, the kind it is read as, and the declaration as written and as refined.""" - - loc: Loc - """The location of the declaration in the document.""" - kind: type[Definition[Any]] - """The kind the member's annotation reads the declaration as.""" - alias: TypeAliasType - """The declaration alias of the member that holds it, which may admit only some definitions of the kind.""" - written: object - """The declaration as the document writes it.""" - json: JSONValue | None - """The declaration refined as JSON; None when it is not JSON.""" - problems: Problems - """Every reason the declaration is not JSON, located in the document.""" - - @dataclass(frozen=True, slots=True) class TypedDocument: """A document's members as its TypedDict types them, before any scope reads its declarations and extension fields.""" members: dict[str, JSONValue] - """Each member the TypedDict declares that has no problem of its type, by key, in the document's order, as refined and parsed; each declaration it holds is refined (None when it is not JSON, which `declarations` reports).""" - declarations: tuple[FoundDeclaration, ...] - """Each declaration the members hold, in the document's order.""" + """Each member the TypedDict declares that has no problem of its type, by key, refined; each declaration in it as refined (None when it is not JSON, which reading it reports).""" + declarations: tuple[_NestedDeclaration, ...] + """Each declaration the members hold, in order, located in the input.""" extension_fields: dict[str, object] """Each member the TypedDict does not declare, by key, as written, for the scope to read.""" problems: Problems """Every reason a member is not what its annotation says, located in the document.""" -class _Refining: - """A leaf parser of a member parsed as written: it refines the value where the leaf sits, so nesting depth counts from the root of the input, and returns the refined value or the reasons it is not JSON.""" - - def __init__(self, refine: Callable[[object, Loc], tuple[JSONValue | None, Problems]]) -> None: - self.refine = refine - - def __call__(self, value: object, loc: Loc) -> Parsed: - refined, found = self.refine(value, loc) - return (value if len(found) != 0 else refined), found - - -class _FindingDeclaration: - """A leaf parser of a member parsed as written, for a member annotated with a declaration alias: it refines the declaration where it sits and passes it on, with any reason it is not JSON, for a scope to read. The declaration itself is never a problem of the member's type.""" - - def __init__(self, kind: type[Definition[Any]], alias: TypeAliasType) -> None: - self.kind = kind - self.alias = alias - - def __call__(self, value: object, loc: Loc) -> Parsed: - refined, found = refine_json(value, loc) - json = refined if len(found) == 0 else None - return FoundDeclaration(loc, self.kind, self.alias, value, json, found), () - - -def _passed_on(value: object, loc: Loc) -> Parsed: - """A leaf parser for a value the refining of its member already checked: passed on as it is.""" - return value, () - - -class _MemberLeaf: - """The leaf `typed_document` compiles a member's parser with, for one way of reading the member, recording whether the annotation holds user data or a declaration alias. - - `refined` reads a member refined as JSON: every JSON value is passed on. - `user` reads a member refined as user data: user data is passed on, - and a JSON value is checked for numbers that are not finite. `written` - reads a member as the document writes it: each JSON value, user data - and declaration is refined where it sits, so one that is not JSON does - not hide a problem elsewhere in the member. - - Only those leaves refine what they read, and only the member itself is - made a tuple when it is an array of another type, so a member read as - written may hold declarations, JSON values and user data, alone or in - one array. Anything else in it raises `TypeError` when the member is - compiled, rather than reading a value that was never refined. So does - a declaration of a kind that refines its declarations its own way, - since the leaf refines it as JSON. - """ - - def __init__(self, way: Literal["refined", "user", "written"]) -> None: - self.way = way - self.user = False - self.nests = False - self.top = True - - def __call__(self, annotation: object) -> Parser | None: - top, self.top = self.top, False - if annotation is UserJSONValue: - self.user = True - return _Refining(refine_user_data) if self.way == "written" else _passed_on - if annotation is JSONValue: - if self.way == "written": - return _Refining(refine_json) - return _passed_on if self.way == "refined" else None - kind = declaration_kind(annotation) - if kind is not None and is_alias(annotation): - if not _refines_as_json(kind): - msg = f"{annotation!r} holds {kind.__name__} declarations, which are not refined as JSON, so a document member cannot hold them" - raise TypeError(msg) - self.nests = True - return _FindingDeclaration(kind, annotation) - if self.way != "written" or (top and get_origin(annotation) is tuple): - return None - msg = f"a document member that holds a declaration may hold only declarations and JSON values, alone or in one array, not {annotation!r}" - raise TypeError(msg) - - -@dataclass(frozen=True, slots=True) -class _Member: - """How `typed_document` reads one member of a document: the parser its annotation compiles to, and how the member is refined before it, if at all.""" - - parse: Parser - refine: Callable[[object, Loc], tuple[JSONValue | None, Problems]] | None - """`refine_json` or `refine_user_data` for a member refined whole before it is parsed; None for a member that holds a declaration, which is parsed as written, each leaf refined where it sits.""" - - -def _member(annotation: object) -> _Member: - """How `typed_document` reads a member annotated `annotation`. - - A member that holds a declaration is parsed as written, so a - declaration that is not JSON is still passed on, and refused by the - scope, without hiding the other declarations of the member. A member - that holds user data is refined as user data, so the parser decides - where a number that is not finite may be. Any other member is refined - as JSON. - """ - probe = _MemberLeaf("refined") - parse = parser(annotation, probe) - if probe.nests: - return _Member(parser(annotation, _MemberLeaf("written")), refine=None) - if probe.user: - return _Member(parser(annotation, _MemberLeaf("user")), refine_user_data) - return _Member(parse, refine_json) - - -@dataclass(frozen=True, slots=True) -class _MemberParsers: - """How `typed_document` reads each member a document's TypedDict declares.""" - - members: Mapping[str, _Member] - required: frozenset[str] - closed: bool - """Whether the TypedDict is closed, so a member it does not declare is an unknown key rather than an extension field.""" - - -@functools.cache -def _member_parsers(shape: type) -> _MemberParsers: - """How `typed_document` reads each member of `shape`, a document's TypedDict, compiled once. - - Raises `TypeError` for an open `shape` whose other keys may hold - anything but user data: `typed_document` passes those on as written, - for the definition that claims each one to read. - """ - keys = typeddict_keys(shape) - if not keys.closed and strip_annotation(keys.extra_items)[0] is not UserJSONValue: - msg = f"{shape.__name__} must be closed, or have extra_items=UserJSONValue, to type a document" - raise TypeError(msg) - return _MemberParsers( - MappingProxyType( - {key: _member(annotation) for key, (annotation, _) in keys.members.items()} - ), - keys.required, - keys.closed, - ) - - -def _as_refined(declaration: FoundDeclaration) -> JSONValue | None: - """A declaration `typed_document` found, as refined: None when it is not JSON.""" - return declaration.json - - -def _typed_member(member: _Member, value: object, at: Loc, key: str) -> tuple[object, Problems]: - """`value`, the member `key` of a document at `at`, read as `member` says: the parsed value and every problem, located in the document.""" - if member.refine is not None: - refined, found = member.refine(value, (*at, key)) - if len(found) != 0: - return None, within(found, at) - return member.parse(refined, (key,)) - # Parsed as written, from the root of the input. A container checks its - # own depth here; each leaf in it checks its own when it is refined. - past = nested_past_the_levels(value, (*at, key)) - if past is not None: - return None, within((past,), at) - if is_array(value) and not is_list_or_tuple(value): - value = tuple(value) - typed, found = member.parse(value, (*at, key)) - return typed, within(found, at) - - def typed_document(doc: Mapping[object, object], shape: type, at: Loc = ()) -> TypedDocument: """Type `doc`, a document at `at`, as `shape`, its TypedDict: the first step of reading a document, before any scope reads its declarations and extension fields. - Each member is checked on its own, so a problem in one does not hide a - problem in another, and is refined once, from the root of the input, - so nesting depth counts from there. The annotation decides where a - number that is not finite may be: in a value annotated - `UserJSONValue` (a node's attributes), and nowhere else. A member - annotated with a declaration alias holds a declaration, which is - refined where it sits and passed on for a scope to read: its envelope - is checked there, by the kind the alias names, and one that is not - JSON is refused there. A member the TypedDict does not declare is an - extension field: what it holds is for the definition in scope that - claims its key, so it is passed on as written. A required member - `doc` lacks, a key that is not a string, and a key a closed TypedDict - does not declare are problems. + The document is checked as any configuration is, by the checker its + TypedDict compiles to, which refines each value where it reads it. So + each member is checked on its own, a problem in one does not hide a + problem in another, nesting depth counts from the root of the input, + and a number that is not finite may be only where the annotation is + `UserJSONValue` (a node's attributes). Each declaration is passed on + for a scope to read, with every reason it is not JSON. A member an open + TypedDict does not declare is an extension field: what it holds is for + the definition in scope that claims its key, so it is passed on as + written. """ - parsers = _member_parsers(shape) - problems: list[ValidationProblem] = [ - ValidationProblem((key,), "missing required key", "missing_key") - for key in sorted(parsers.required - doc.keys()) - ] - members: dict[str, JSONValue] = {} - declarations: list[FoundDeclaration] = [] + keys = typeddict_keys(shape) extension_fields: dict[str, object] = {} - for key, value in doc.items(): - if not isinstance(key, str): - message = f"non-string top-level key {shown_key(key)}" - problems.append(ValidationProblem((), message, "invalid_type")) - continue - member = parsers.members.get(key) - if member is None: - if parsers.closed: - problems.append(ValidationProblem((key,), f"unexpected key {key!r}", "unknown_key")) - else: + declared: Mapping[object, object] = doc + if not keys.closed: + declared = {} + for key, value in doc.items(): + if isinstance(key, str) and key not in keys.members: extension_fields[key] = value - continue - typed, found = _typed_member(member, value, at, key) - problems.extend(found) - if len(found) != 0: - continue - if member.refine is not None: - members[key] = cast("JSONValue", typed) - continue - found_here: list[FoundDeclaration] = [] - _collect(typed, FoundDeclaration, found_here) - members[key] = cast("JSONValue", _putting_back(typed, FoundDeclaration, _as_refined)) - if len(at) == 0: - declarations.extend(found_here) - else: - # Built directly: `dataclasses.replace` costs more than the - # rest of the move, for every declaration in a listing. - declarations.extend( - FoundDeclaration( - each.loc[len(at) :], - each.kind, - each.alias, - each.written, - each.json, - within(each.problems, at), - ) - for each in found_here - ) - return TypedDocument(members, tuple(declarations), extension_fields, tuple(problems)) - - -@functools.cache -def _refines_as_json(kind: type[Definition[Any]]) -> bool: - """Whether `kind` refines its declarations as JSON, as `Definition._refined` does, rather than its own way.""" - return not any( - "_refined" in vars(base) for base in kind.__mro__[: kind.__mro__.index(Definition)] + else: + declared[key] = value + typed, found = _checker(shape).parse(declared, at) + problems = within(found, at) + # A member with a problem comes back as written, at any depth, so only + # the members that typed cleanly are kept and searched for declarations. + # The checker builds a new object unless the document is refused whole. + wrong = {problem.loc[0] for problem in problems if len(problem.loc) != 0} + kept = ( + {} + if typed is declared + else { + key: value + for key, value in cast("dict[str, object]", typed).items() + if key not in wrong + } ) + declaring = _declaring(shape) + nested: list[_NestedDeclaration] = [] + members: dict[str, JSONValue] = {} + for key, value in kept.items(): + if key in declaring: + start = len(nested) + _collect(value, nested) + value = _put_back(value, _as_written, nested[start:]) + members[key] = cast("JSONValue", value) + return TypedDocument(members, tuple(nested), extension_fields, problems) def read_found( - declaration: FoundDeclaration, context: Context, at: Loc = () + declaration: _NestedDeclaration, context: Context, at: Loc = () ) -> tuple[ResolvedDeclaration[Any], Problems]: """Read `declaration`, which `typed_document` found in a document at `at`, in `context`, as `resolve` reads it, and check that the member's alias admits the definition that read it. The problems are located in the document. `typed_document` refined the declaration as JSON, which is how its - kind refines declarations (a member cannot hold a kind that refines - them otherwise), so it is read without being refined again. + kind refines declarations, so it is read without being refined again. """ - loc = (*at, *declaration.loc) resolved, found = resolve_refined( declaration.written, declaration.json, - _located(at, declaration.problems), + declaration.problems, declaration.kind, context, - loc, + declaration.loc, ) - placed = _NestedDeclaration(loc, declaration.kind, declaration.json, declaration.alias) - return resolved, within((*found, *_sized(placed, resolved)), at) + return resolved, within((*found, *_sized(declaration, resolved)), at) def named_configuration( @@ -2245,7 +2054,6 @@ def _replaced(value: JSONValue, path: Loc, new: JSONValue) -> JSONValue: "C", "Context", "Definition", - "FoundDeclaration", "Nested", "Problems", "RefusedDeclaration", diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py index 34b290dac5..6d6c7e7547 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py @@ -216,8 +216,8 @@ def read_array_v3( for declaration in typed.declarations: resolved, found = read_found(declaration, context, at) problems.extend(found) - key = cast("str", declaration.loc[0]) - if len(declaration.loc) == 1: + key = cast("str", declaration.loc[len(at)]) + if len(declaration.loc) == len(at) + 1: read[key] = resolved else: listed.setdefault(key, []).append(resolved) diff --git a/packages/zarr-metadata/tests/model/test_array.py b/packages/zarr-metadata/tests/model/test_array.py index debcc198be..875a1770aa 100644 --- a/packages/zarr-metadata/tests/model/test_array.py +++ b/packages/zarr-metadata/tests/model/test_array.py @@ -2292,7 +2292,9 @@ def test_missing_key_kind_is_machine_readable() -> None: del doc["chunk_key_encoding"] problems = read_array_metadata_v3(doc).problems assert problems == ( - ValidationProblem(("chunk_key_encoding",), "missing required key", "missing_key"), + ValidationProblem( + ("chunk_key_encoding",), "missing required key 'chunk_key_encoding'", "missing_key" + ), ) @@ -2767,13 +2769,10 @@ def test_a_problem_shows_a_value_nested_too_deep_to_write_by_saying_so() -> None (problem.loc, problem.kind, problem.message) for problem in read_array_metadata_v2(document).problems ] == [(("zarr_format",), "invalid_type", "expected 2, got a value nested too deep to show")] - # A v3 document's `zarr_format` is refined before its annotation checks - # it, so the depth rule reports the container past the cap. - (problem,) = read_array_metadata_v3( - {**ZarrV3ArrayMetadata.create_default().to_json(), "zarr_format": deep} - ).problems - assert (problem.loc[0], problem.kind, problem.message) == ( - "zarr_format", - "invalid_value", - f"nested deeper than the {JSON_DEPTH} levels a reader walks", - ) + # A v3 document's `zarr_format` is refused the same way. + assert [ + (problem.loc, problem.kind, problem.message) + for problem in read_array_metadata_v3( + {**ZarrV3ArrayMetadata.create_default().to_json(), "zarr_format": deep} + ).problems + ] == [(("zarr_format",), "invalid_type", "expected 3, got a value nested too deep to show")] diff --git a/packages/zarr-metadata/tests/model/test_pydantic_module.py b/packages/zarr-metadata/tests/model/test_pydantic_module.py index 9ada570aed..4a4866e58d 100644 --- a/packages/zarr-metadata/tests/model/test_pydantic_module.py +++ b/packages/zarr-metadata/tests/model/test_pydantic_module.py @@ -111,7 +111,7 @@ class Manifest(BaseModel): assert (error["type"], error["loc"], error["msg"]) == ( "missing_key", ("metadata", "chunk_key_encoding"), - "missing required key", + "missing required key 'chunk_key_encoding'", ) # For a missing key, the input is the object that lacks the key, as in pydantic's own errors. assert error["input"] == doc diff --git a/packages/zarr-metadata/tests/model/test_read_array_metadata.py b/packages/zarr-metadata/tests/model/test_read_array_metadata.py index 937abcea5f..b1d775881c 100644 --- a/packages/zarr-metadata/tests/model/test_read_array_metadata.py +++ b/packages/zarr-metadata/tests/model/test_read_array_metadata.py @@ -379,7 +379,8 @@ def test_error_a_document_without_a_declaration_reads_it_as_unset(member: str) - reading = read_array_metadata_v3(document) assert getattr(reading, member) is UNSET assert (member,) not in [loc for loc, _ in reading.declarations()] - assert ValidationProblem((member,), "missing required key", "missing_key") in reading.problems + missing = ValidationProblem((member,), f"missing required key {member!r}", "missing_key") + assert missing in reading.problems def test_error_a_document_without_a_shape_hands_its_codecs_chunks_of_no_known_rank() -> None: diff --git a/packages/zarr-metadata/tests/model/test_typed_document.py b/packages/zarr-metadata/tests/model/test_typed_document.py index 75cb52a08d..36985feeda 100644 --- a/packages/zarr-metadata/tests/model/test_typed_document.py +++ b/packages/zarr-metadata/tests/model/test_typed_document.py @@ -3,18 +3,14 @@ from __future__ import annotations import json -from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING import pytest -from typing_extensions import TypeAliasType, TypedDict +from typing_extensions import TypedDict -from zarr_metadata._common import JSONValue, UserJSONValue -from zarr_metadata._json import JSON_DEPTH, Problems, refine_user_data -from zarr_metadata.definition import Definition -from zarr_metadata.definition._definition import typed_document +from zarr_metadata._common import UserJSONValue +from zarr_metadata._json import JSON_DEPTH from zarr_metadata.model import ZarrV3ArrayMetadata, read_array_metadata_v3 -from zarr_metadata.v3._common import ZarrV3CodecDeclaration, ZarrV3DeclarationJSON from zarr_metadata.v3.definition import CORE_CONTEXT, ArrayExtraFieldDefinition, ZarrV3Context if TYPE_CHECKING: @@ -133,54 +129,3 @@ def test_every_problem_in_a_document_is_reported( assert found == expected if "acme.note" in doc: assert "acme.note" in reading.extra_fields - - -class _PairDocument(TypedDict, closed=True): - pair: tuple[ZarrV3CodecDeclaration, float] - - -class _NestedDocument(TypedDict, closed=True): - nested: tuple[tuple[ZarrV3CodecDeclaration, ...], ...] - - -class _OpenDocument(TypedDict): - codec: ZarrV3CodecDeclaration - - -_OwnWayDeclaration = TypeAliasType("_OwnWayDeclaration", ZarrV3DeclarationJSON) - - -@dataclass(frozen=True, kw_only=True, slots=True, repr=False) -class _OwnWayDefinition(Definition[Any], kind=True, format=3): - label: ClassVar[str] = "own-way declaration" - declaration_aliases: ClassVar[tuple[TypeAliasType, ...]] = (_OwnWayDeclaration,) - - @classmethod - def _refined( - cls, data: object, loc: Loc, definition: Definition[Any] | None - ) -> tuple[JSONValue | None, Problems]: - return refine_user_data(data, loc) - - -class _OwnWayDocument(TypedDict, closed=True): - own: _OwnWayDeclaration - - -def test_error_a_member_holding_a_declaration_and_a_scalar_is_not_compiled() -> None: - with pytest.raises(TypeError, match="may hold only declarations and JSON values"): - typed_document({}, _PairDocument) - - -def test_error_a_member_holding_declarations_in_nested_arrays_is_not_compiled() -> None: - with pytest.raises(TypeError, match="may hold only declarations and JSON values"): - typed_document({}, _NestedDocument) - - -def test_error_a_member_holding_a_kind_that_refines_its_own_way_is_not_compiled() -> None: - with pytest.raises(TypeError, match="which are not refined as JSON"): - typed_document({}, _OwnWayDocument) - - -def test_error_a_document_whose_other_keys_are_not_user_data_is_not_compiled() -> None: - with pytest.raises(TypeError, match="must be closed, or have extra_items=UserJSONValue"): - typed_document({}, _OpenDocument) diff --git a/packages/zarr-metadata/tests/test_typed_json.py b/packages/zarr-metadata/tests/test_typed_json.py index 292abe8cd2..bbda9cb52d 100644 --- a/packages/zarr-metadata/tests/test_typed_json.py +++ b/packages/zarr-metadata/tests/test_typed_json.py @@ -18,7 +18,9 @@ import sys import textwrap import types +from collections import UserList from collections.abc import Mapping +from enum import IntEnum, StrEnum from typing import ( TYPE_CHECKING, Annotated, @@ -53,6 +55,8 @@ import zarr_metadata.definition import zarr_metadata.v2 import zarr_metadata.v3 +from zarr_metadata._common import UserJSONValue +from zarr_metadata._json import JSON_DEPTH from zarr_metadata._typed_json import ( Parsed, Parser, @@ -87,6 +91,14 @@ Width = TypeAliasType("Width", int) +class Color(StrEnum): + RED = "red" + + +class Size(IntEnum): + LARGE = 3 + + class Options(TypedDict, closed=True): level: int note: NotRequired[str] @@ -172,7 +184,7 @@ def _found(parsed: Parsed) -> list[tuple[Loc, str]]: (tuple[str | None, ...], ["a", None], ("a", None)), (int | str, "a", "a"), (Mapping[str, int], {"k": 1}, {"k": 1}), - (JSONValue, {"any": [1, None]}, {"any": [1, None]}), + (JSONValue, {"any": [1, None]}, {"any": (1, None)}), (Level, 5, 5), (Width, 5, 5), ], @@ -199,10 +211,74 @@ def test_a_value_of_the_shape_reads_as_itself( annotation: object, value: object, parsed: object ) -> None: # The shapes JSON values take, and no others, each compiled once from its - # annotation. An array is returned as a tuple; other values unchanged. + # annotation. An array is returned as a tuple, also inside a JSON value; + # other values unchanged. assert _read(annotation, value) == (parsed, ()) +@pytest.mark.parametrize( + ("annotation", "value", "parsed"), + [ + (str, Color.RED, "red"), + (int, Size.LARGE, 3), + (Literal["red"], Color.RED, "red"), + (Literal[3], Size.LARGE, 3), + (tuple[int, ...], UserList([1, 2]), (1, 2)), + (tuple[str, int], UserList([Color.RED, Size.LARGE]), ("red", 3)), + (str | tuple[str, ...], UserList([Color.RED]), ("red",)), + (Mapping[str, int], types.MappingProxyType({"a": Size.LARGE}), {"a": 3}), + (JSONValue, {"a": UserList([Color.RED])}, {"a": ("red",)}), + (UserJSONValue, [math.inf], (math.inf,)), + (Mapping[str, UserJSONValue], {"a": math.nan}, {"a": math.nan}), + ], + ids=[ + "str-enum", + "int-enum", + "literal-of-a-str-enum", + "literal-of-an-int-enum", + "sequence", + "fixed-tuple", + "union", + "mapping-proxy", + "json", + "user-data", + "user-data-in-a-mapping", + ], +) +def test_a_value_as_a_document_holds_it_reads_as_its_json( + annotation: object, value: object, parsed: object +) -> None: + # A parser refines what it reads: a value that stands for JSON reads as + # that JSON, and a number need not be finite where the annotation is + # `UserJSONValue`. + typed, found = _read(annotation, value) + assert found == () + # Compared as JSON text, so that NaN equals itself and a type is checked. + assert json.dumps(typed) == json.dumps(parsed) + assert type(typed) is type(parsed) + + +@pytest.mark.parametrize( + ("annotation", "value", "loc"), + [ + (float, math.nan, ()), + (JSONValue, {"a": math.inf}, ("a",)), + (tuple[float, ...], [1.0, math.nan], (1,)), + ], + ids=["float", "json", "sequence"], +) +def test_error_a_number_that_is_not_finite_is_not_json_where_the_annotation_says_json( + annotation: object, value: object, loc: Loc +) -> None: + assert _found(_read(annotation, value)) == [(loc, "invalid_value")] + + +def test_error_an_array_past_the_levels_is_refused_where_it_sits() -> None: + # Counted from the root: the location says how deep the value already is. + deep = parser(tuple[int, ...], no_leaf)([1], (0,) * JSON_DEPTH) + assert _found(deep) == [((0,) * JSON_DEPTH, "invalid_value")] + + @pytest.mark.parametrize( ("annotation", "value", "loc", "kind"), [ @@ -272,7 +348,7 @@ def test_error_a_value_of_another_shape_is_located( {"level": 1, "more": "two"}, [(("more",), "invalid_type")], ), - (Open, {"level": 1, "more": [2]}, {"level": 1, "more": [2]}, []), + (Open, {"level": 1, "more": [2]}, {"level": 1, "more": (2,)}, []), (Small | Large, {"x": 1, "y": 2}, {"x": 1, "y": 2}, []), (Small | Large, {"x": 1, "z": 2}, {"x": 1}, [(("z",), "unknown_key")]), (Option1 | Option2, {"two": [1]}, {"two": (1,)}, []), @@ -1835,7 +1911,7 @@ def test_error_check_names_what_no_parser_reads() -> None: ({"level": 1, "note": math.inf}, ("note",), "invalid_value"), ({"level": 1, 2: 3}, (), "invalid_type"), ({"level": 1, "note": {1}}, ("note",), "invalid_type"), - ({"level": 1, "note": [{3: 1}]}, ("note", 0), "invalid_type"), + ({"level": 1, "note": {"a": [{3: 1}]}}, ("note",), "invalid_type"), ], ids=[ "nan", @@ -1848,7 +1924,9 @@ def test_error_check_names_what_no_parser_reads() -> None: def test_error_check_locates_a_value_that_is_not_json( value: dict[object, object], loc: Loc, kind: str ) -> None: - # Rejected before any TypedDict is checked: `check` compares only JSON values. + # Each value is refined where the TypedDict reads it: a part that is not + # JSON is reported where it sits, and a member of the wrong type is + # reported once, whatever it holds. typed, problems = check(value, Options) assert typed is None assert [(problem.loc, problem.kind) for problem in problems] == [(loc, kind)] From 074377cd8daa244633c7ef7f990423f9a23fa568 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 10:56:42 +0100 Subject: [PATCH 08/27] fix(zarr-metadata): read declarations in configurations as documents read them Review of e2ecccad3 found the configuration path half migrated to the refining checker: - A nested declaration that is not JSON (a NaN in a codec held by a `finite=False` configuration) was read as null and reported as "got null" at the declaration. `_envelope` now reports why it is not JSON, and the configuration's nested-declaration loop refuses it through `resolve_refined`, as a document's declarations are; `_moved` locates the declaration and its problems together. - `typed_json.check` returned a value when a closed TypedDict's undeclared key held a value that is not JSON. `object_of` now refines that value as user data, so it is reported but may hold any number. - A declaration that writes no configuration at the last level a reader walks was refused, because the empty configuration made up for it was depth-checked. It is no longer checked: it is not in the input. A number that is not finite now stands only where the annotation is `UserJSONValue`, also in a `finite=False` configuration, whose `float` members accepted one before. The `finite` docstrings say so. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../src/zarr_metadata/_typed_json.py | 4 ++ .../zarr_metadata/definition/_definition.py | 39 +++++++++--- .../src/zarr_metadata/v3/_definition.py | 6 +- .../tests/model/test_typed_document.py | 62 ++++++++++++++++++- .../zarr-metadata/tests/test_typed_json.py | 15 +++++ 5 files changed, 112 insertions(+), 14 deletions(-) diff --git a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py index 2ddddd002d..a16c8a2030 100644 --- a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py @@ -869,6 +869,10 @@ def parse(value: object, loc: Loc) -> Parsed: continue if extra is None: found.extend(problem((*loc, key), f"unexpected key {key!r}", "unknown_key")) + # Left out, and not read, so like an unclaimed extension + # field it may hold any number; a value that is not JSON in + # any other way is still a problem, whatever key holds it. + found.extend(refine_user_data(entry, (*loc, key))[1]) continue parsed[key], problems = extra(entry, (*loc, key)) found.extend(problems) diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index b74afe1153..07fd28c75f 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -879,10 +879,21 @@ def _located(prefix: Loc, problems: Iterable[ValidationProblem]) -> Problems: def _envelope(declaration: _NestedDeclaration) -> Problems: - """The problems with a nested declaration's envelope, located at the declaration.""" + """The problems with a nested declaration's envelope, located at the declaration; for a declaration that is not JSON, every reason it is not.""" + if len(declaration.problems) != 0: + return declaration.problems return _located(declaration.loc, declaration.kind._envelope_problems(declaration.json)) +def _moved(declaration: _NestedDeclaration, loc: Loc) -> _NestedDeclaration: + """`declaration`, with it and the reasons it is not JSON located at `loc`.""" + problems = tuple( + dataclasses.replace(each, loc=(*loc, *each.loc[len(declaration.loc) :])) + for each in declaration.problems + ) + return dataclasses.replace(declaration, loc=loc, problems=problems) + + def _configuration_checked( value: object, shape: type[T], loc: Loc = (), *, finite: bool = True ) -> tuple[T | None, Problems]: @@ -895,9 +906,8 @@ def _configuration_checked( member is an unknown key: it is reported and left out, and the value is still returned. This matches how the checker reports and leaves out a key that a closed TypedDict does not declare. A number that is not - finite is a problem unless `finite` is false, for a configuration that - holds user data; the TypedDict still decides where such a number may - be. + finite is a problem, except where the TypedDict says `UserJSONValue` + and `finite` is false, for a configuration that holds user data. """ refined, problems = (refine_json if finite else refine_user_data)(value, loc) if len(problems) != 0: @@ -1773,7 +1783,11 @@ def _read( return RefusedDeclaration( json=data, name=name, read_as=kind, definition=definition ), missing - typed, found, nested = _typed(definition.configuration, {} if given is None else given, at) + # A declaration that writes no configuration has the empty one, which + # the check above found its definition accepts. It is not in the input, + # so no rule of the input (such as its depth) applies to it. + empty: tuple[object, Problems, tuple[_NestedDeclaration, ...]] = ({}, (), ()) + typed, found, nested = empty if given is None else _typed(definition.configuration, given, at) # Read the nested declarations first, each one stack frame deeper, so the # rules see them as the scope read them. Each is put back as a document # writes it, so the configuration shows what was read, however each was @@ -1784,12 +1798,17 @@ def _read( inside: list[ValidationProblem] = [] for declaration in nested: place = declaration.loc[len(at) :] - placed = dataclasses.replace(declaration, loc=kind._in_configuration(loc, place)) - inside.extend(_envelope(placed)) - inner, found_inside = _read(declaration.json, declaration.kind, context, placed.loc) + placed = _moved(declaration, kind._in_configuration(loc, place)) + if len(placed.problems) != 0: + # Not JSON, so refused as a document's declarations are. It has + # no name `_named` reads, so no configuration is built from it. + inner, found_inside = resolve_refined( + placed.written, None, placed.problems, placed.kind, context, placed.loc + ) + else: + inside.extend(_envelope(placed)) + inner, found_inside = _read(placed.json, placed.kind, context, placed.loc) within[place] = inner - # The input was refined JSON, so the result is JSON, or a declaration - # refused for its contents, never for not being JSON. written[declaration.loc] = cast("JSONValue", document_json(inner)) inside.extend(found_inside) inside.extend(_sized(placed, inner)) diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py index dc4a3135b1..fadaedf6ce 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py @@ -523,7 +523,9 @@ class ExtraFieldDefinition(Definition[C]): `finite` says whether every number in the member must be finite, as RFC 8259 JSON requires. A member that holds user data sets it to False: consolidated metadata holds node documents, whose attributes - may hold `NaN`, `Infinity` and `-Infinity`. A member that nothing + may hold `NaN`, `Infinity` and `-Infinity`. Even then, such a number + may stand only where the configuration's annotation is + `UserJSONValue`, as a node's attributes are. A member that nothing claims is not read, so like attributes it may hold any number. The spec lets every extension field carry `"must_understand": false`, @@ -535,7 +537,7 @@ class ExtraFieldDefinition(Definition[C]): """ finite: bool = True - """Whether every number in the member must be finite.""" + """Whether every number in the member must be finite, even where the configuration says `UserJSONValue`.""" spec_members: ClassVar[frozenset[str]] = frozenset() """The members the spec defines in a document this kind reads extra fields of, which are never extra fields.""" diff --git a/packages/zarr-metadata/tests/model/test_typed_document.py b/packages/zarr-metadata/tests/model/test_typed_document.py index 36985feeda..a4cfab0a90 100644 --- a/packages/zarr-metadata/tests/model/test_typed_document.py +++ b/packages/zarr-metadata/tests/model/test_typed_document.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import math from typing import TYPE_CHECKING import pytest @@ -10,8 +11,15 @@ from zarr_metadata._common import UserJSONValue from zarr_metadata._json import JSON_DEPTH +from zarr_metadata.definition import AcceptedDeclaration, resolve from zarr_metadata.model import ZarrV3ArrayMetadata, read_array_metadata_v3 -from zarr_metadata.v3.definition import CORE_CONTEXT, ArrayExtraFieldDefinition, ZarrV3Context +from zarr_metadata.v3._common import ZarrV3CodecDeclaration +from zarr_metadata.v3.definition import ( + CORE_CONTEXT, + ArrayExtraFieldDefinition, + DataTypeDefinition, + ZarrV3Context, +) if TYPE_CHECKING: from zarr_metadata._typed_json import Loc @@ -32,15 +40,27 @@ class _Note(TypedDict, closed=True): must_understand: bool +class _Mix(TypedDict, closed=True): + codec: ZarrV3CodecDeclaration + scale: float + note: UserJSONValue + must_understand: bool + + _NOTE_CONTEXT = CORE_CONTEXT.union( ZarrV3Context( array_extra_fields=[ - ArrayExtraFieldDefinition(name="acme.note", configuration=_Note, finite=False) + ArrayExtraFieldDefinition(name="acme.note", configuration=_Note, finite=False), + ArrayExtraFieldDefinition(name="acme.mix", configuration=_Mix, finite=False), ] ) ) +def _mix(codec: object, scale: object) -> dict[str, object]: + return {"codec": codec, "scale": scale, "note": math.nan, "must_understand": True} + + def _array(**members: object) -> dict[str, object]: doc = json.loads(json.dumps(ZarrV3ArrayMetadata.create_default(shape=(4,)).to_json())) return {**doc, **members} @@ -106,6 +126,29 @@ def _array(**members: object) -> dict[str, object]: _NOTE_CONTEXT, set(), ), + # A definition that allows user data allows a number that is not + # finite only where its configuration says `UserJSONValue`: not in a + # number, and not in a declaration it holds, which is reported where + # it is not JSON. + ( + _array(**{"acme.mix": _mix({"name": "bytes"}, 1.5)}), + _NOTE_CONTEXT, + set(), + ), + ( + _array( + **{ + "acme.mix": _mix( + {"name": "bytes", "configuration": {"endian": math.nan}}, math.inf + ) + } + ), + _NOTE_CONTEXT, + { + (("acme.mix", "codec", "configuration", "endian"), "invalid_value"), + (("acme.mix", "scale"), "invalid_value"), + }, + ), ], ids=[ "non-json-codec", @@ -113,6 +156,8 @@ def _array(**members: object) -> dict[str, object]: "bad-level-and-deep", "claimed-deep", "claimed-nan", + "user-data-where-annotated", + "not-finite-elsewhere", ], ) def test_every_problem_in_a_document_is_reported( @@ -129,3 +174,16 @@ def test_every_problem_in_a_document_is_reported( assert found == expected if "acme.note" in doc: assert "acme.note" in reading.extra_fields + + +@pytest.mark.parametrize("declaration", ["uint8", {"name": "uint8"}], ids=["name", "object"]) +def test_a_declaration_without_a_configuration_reads_up_to_the_last_level( + declaration: object, +) -> None: + # The empty configuration such a declaration has is not in the input, + # so it is not counted as a level below it. + resolved, problems = resolve( + declaration, DataTypeDefinition, CORE_CONTEXT, ("x",) * (JSON_DEPTH - 1) + ) + assert problems == () + assert isinstance(resolved, AcceptedDeclaration) diff --git a/packages/zarr-metadata/tests/test_typed_json.py b/packages/zarr-metadata/tests/test_typed_json.py index bbda9cb52d..a54e75ef44 100644 --- a/packages/zarr-metadata/tests/test_typed_json.py +++ b/packages/zarr-metadata/tests/test_typed_json.py @@ -1932,6 +1932,21 @@ def test_error_check_locates_a_value_that_is_not_json( assert [(problem.loc, problem.kind) for problem in problems] == [(loc, kind)] +@pytest.mark.parametrize( + "junk", [object(), b"x", {1: 2}], ids=["object", "bytes", "non-string-key"] +) +def test_error_check_refuses_a_value_that_is_not_json_under_an_undeclared_key( + junk: object, +) -> None: + # The key is reported and left out, and what it holds is still checked. + typed, problems = check({"level": 1, "junk": junk}, Options) + assert typed is None + assert [(problem.loc, problem.kind) for problem in problems] == [ + (("junk",), "unknown_key"), + (("junk",), "invalid_type"), + ] + + def test_error_check_refuses_null() -> None: # JSON null is valid JSON but not an object. Refining it gives `None` # with no problem, which would not be a usable result. From da32aeb83574d819b25b97612f7cb6839edbdbdc Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 11:23:59 +0100 Subject: [PATCH 09/27] fix(zarr-metadata): share the unwritten-configuration rule between both readers and refine undeclared values strictly A declaration that writes no configuration has the empty one, which is not in the input; `_read` and `_read_carried` now share `_given`, so neither counts it as a level (a carried data type such as `r16` at the last level was refused). A value under a key a TypedDict does not declare is refined by `refine_json`: no annotation says it may hold a number that is not finite, so `finite=False` no longer lets one through there. The unused `_checked` is removed. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../src/zarr_metadata/_typed_json.py | 8 ++-- .../zarr_metadata/definition/_definition.py | 37 +++++++++---------- .../tests/model/test_typed_document.py | 33 +++++++++++++++-- .../zarr-metadata/tests/test_typed_json.py | 16 ++++++-- 4 files changed, 63 insertions(+), 31 deletions(-) diff --git a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py index a16c8a2030..940333605c 100644 --- a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py @@ -869,10 +869,10 @@ def parse(value: object, loc: Loc) -> Parsed: continue if extra is None: found.extend(problem((*loc, key), f"unexpected key {key!r}", "unknown_key")) - # Left out, and not read, so like an unclaimed extension - # field it may hold any number; a value that is not JSON in - # any other way is still a problem, whatever key holds it. - found.extend(refine_user_data(entry, (*loc, key))[1]) + # Left out, but still refined: a value that is not JSON is + # a problem whatever key holds it, and no annotation says + # this one may hold a number that is not finite. + found.extend(refine_json(entry, (*loc, key))[1]) continue parsed[key], problems = extra(entry, (*loc, key)) found.extend(problems) diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index 07fd28c75f..8ecee5e300 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -594,7 +594,7 @@ class _NestedDeclaration: """A declaration that the check found in a configuration or a document: its location, its kind, and its JSON. The checker returns this in place of the JSON wherever a declaration alias - appears. `_checked` collects each one and puts its JSON back. It is + appears. `_typed` collects each one, and its caller puts its JSON back. It is carried in the value instead of being recorded separately, so a union branch that did not match leaves nothing behind. """ @@ -742,14 +742,6 @@ def _declaring(shape: type) -> frozenset[str]: return frozenset(held) -def _checked( - shape: type, value: object, loc: Loc -) -> tuple[object, Problems, tuple[_NestedDeclaration, ...]]: - """Check `value` as `shape`. Return the typed value (with each nested declaration restored as written), every problem, and the nested declarations in order.""" - typed, found, nested = _typed(shape, value, loc) - return _put_back(typed, _as_written, nested), found, nested - - def _typed( shape: type, value: object, loc: Loc ) -> tuple[object, Problems, tuple[_NestedDeclaration, ...]]: @@ -1783,11 +1775,7 @@ def _read( return RefusedDeclaration( json=data, name=name, read_as=kind, definition=definition ), missing - # A declaration that writes no configuration has the empty one, which - # the check above found its definition accepts. It is not in the input, - # so no rule of the input (such as its depth) applies to it. - empty: tuple[object, Problems, tuple[_NestedDeclaration, ...]] = ({}, (), ()) - typed, found, nested = empty if given is None else _typed(definition.configuration, given, at) + typed, found, nested = _given(definition.configuration, given, at) # Read the nested declarations first, each one stack frame deeper, so the # rules see them as the scope read them. Each is put back as a document # writes it, so the configuration shows what was read, however each was @@ -1882,6 +1870,21 @@ def _named(declaration: _NestedDeclaration) -> bool: return name is not None and len(malformed) == 0 +def _given( + shape: type, given: Mapping[str, object] | None, at: Loc +) -> tuple[object, Problems, tuple[_NestedDeclaration, ...]]: + """`given`, the configuration a declaration writes at `at`, checked as `shape`, as `_typed` checks it. + + A declaration that writes no configuration has the empty one, which its + caller has found the definition accepts. It is not in the input, so no + rule of the input (such as its depth) applies to it, and it is not + checked. + """ + if given is None: + return {}, (), () + return _typed(shape, given, at) + + def _read_carried( data: JSONValue, name: str, @@ -1898,11 +1901,7 @@ def _read_carried( problem of the declaration. A configuration written next to the name must be empty, so each member in it is an undeclared key. """ - _, beside, _ = _checked( - EmptyConfiguration, - {} if given is None else given, - kind._in_configuration(loc, ()), - ) + _, beside, _ = _given(EmptyConfiguration, given, kind._in_configuration(loc, ())) # A name is a single token, so a part the definition does not declare is # a wrong value of the name, not an unknown key a reader may leave out. # The parts it does not declare are reported in one problem, by how the diff --git a/packages/zarr-metadata/tests/model/test_typed_document.py b/packages/zarr-metadata/tests/model/test_typed_document.py index a4cfab0a90..58177310e6 100644 --- a/packages/zarr-metadata/tests/model/test_typed_document.py +++ b/packages/zarr-metadata/tests/model/test_typed_document.py @@ -11,7 +11,7 @@ from zarr_metadata._common import UserJSONValue from zarr_metadata._json import JSON_DEPTH -from zarr_metadata.definition import AcceptedDeclaration, resolve +from zarr_metadata.definition import AcceptedDeclaration, RefusedDeclaration, resolve from zarr_metadata.model import ZarrV3ArrayMetadata, read_array_metadata_v3 from zarr_metadata.v3._common import ZarrV3CodecDeclaration from zarr_metadata.v3.definition import ( @@ -172,11 +172,36 @@ def test_every_problem_in_a_document_is_reported( for problem in reading.problems } assert found == expected - if "acme.note" in doc: - assert "acme.note" in reading.extra_fields + # Each problem is reported once. + assert len({(problem.loc, problem.kind) for problem in reading.problems}) == len( + reading.problems + ) + # A claimed extension field is placed by its definition, refused when it + # has a problem. + for key in ("acme.note", "acme.mix"): + if key in doc: + refused = any(loc[0] == key for loc, _ in expected) + assert isinstance(reading.extra_fields[key], RefusedDeclaration) is refused + + +def test_error_a_configuration_refuses_a_declaration_in_it_that_is_not_json() -> None: + # Without a scope, as with one: the declaration is not JSON, and that is + # reported where it is not. + definition = ArrayExtraFieldDefinition(name="acme.mix", configuration=_Mix, finite=False) + configuration, problems = definition.read_configuration( + _mix({"name": "bytes", "configuration": {"endian": math.nan}}, 1.5) + ) + assert configuration is None + assert [(problem.loc, problem.kind) for problem in problems] == [ + (("codec", "configuration", "endian"), "invalid_value") + ] -@pytest.mark.parametrize("declaration", ["uint8", {"name": "uint8"}], ids=["name", "object"]) +@pytest.mark.parametrize( + "declaration", + ["uint8", {"name": "uint8"}, "r16", {"name": "r16"}], + ids=["name", "object", "carried-name", "carried-object"], +) def test_a_declaration_without_a_configuration_reads_up_to_the_last_level( declaration: object, ) -> None: diff --git a/packages/zarr-metadata/tests/test_typed_json.py b/packages/zarr-metadata/tests/test_typed_json.py index a54e75ef44..42f1696ca6 100644 --- a/packages/zarr-metadata/tests/test_typed_json.py +++ b/packages/zarr-metadata/tests/test_typed_json.py @@ -1933,17 +1933,25 @@ def test_error_check_locates_a_value_that_is_not_json( @pytest.mark.parametrize( - "junk", [object(), b"x", {1: 2}], ids=["object", "bytes", "non-string-key"] + ("junk", "kind"), + [ + (object(), "invalid_type"), + (b"x", "invalid_type"), + ({1: 2}, "invalid_type"), + (math.nan, "invalid_value"), + ], + ids=["object", "bytes", "non-string-key", "nan"], ) def test_error_check_refuses_a_value_that_is_not_json_under_an_undeclared_key( - junk: object, + junk: object, kind: str ) -> None: - # The key is reported and left out, and what it holds is still checked. + # The key is reported and left out, and what it holds is still checked: + # no annotation says it may hold a number that is not finite. typed, problems = check({"level": 1, "junk": junk}, Options) assert typed is None assert [(problem.loc, problem.kind) for problem in problems] == [ (("junk",), "unknown_key"), - (("junk",), "invalid_type"), + (("junk",), kind), ] From b88c12142fdab3e4f8d52268ab9334f9c26893ba Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 11:37:37 +0100 Subject: [PATCH 10/27] fix(zarr-metadata): refine what an unexpected consolidated envelope member holds `read_consolidated_metadata_v3` reported a member the envelope does not declare but did not refine its value, while the group reader, which types the same envelope with the checker, does. A value that is not JSON, or a number that is not finite, under such a member is now reported by both. The package docstring says an unknown key's value must still be JSON, and a test pins NaN under an undeclared key of a `finite=False` extension field. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../src/zarr_metadata/definition/__init__.py | 6 ++- .../src/zarr_metadata/model/_group_v3.py | 8 +++- .../tests/model/test_typed_document.py | 40 ++++++++++++++++++- 3 files changed, 50 insertions(+), 4 deletions(-) diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py index df2f4905a7..6cb5066d22 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py @@ -88,8 +88,10 @@ kind)`, with `kind` one of `invalid_type`, `invalid_value`, `missing_key`, `unknown_key` and `invalid_json`. A declaration with an unknown key is still read: the key is reported, and the configuration -is checked without it. So a consumer that tolerates unknown keys can -filter problems by kind and use the result. The declaration is valid only +is checked without it. What the key holds must still be JSON, with every +number finite, since no annotation admits anything else there. So a +consumer that tolerates unknown keys can filter problems by kind and use +the result. The declaration is valid only when there are no problems at all. Each problem stores the content of its message as data, as pydantic's errors and zod's issues do: `input` is the value found at `loc` (the `12` above), and `ctx` is what was diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py index 6685c1cff3..33f7bee027 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py @@ -29,6 +29,7 @@ not_an_object, outside_of, prefixed, + refine_json, refine_user_data, said, shown, @@ -987,7 +988,7 @@ def read_group_v3( def _envelope_problems(member: Mapping[object, object]) -> list[ValidationProblem]: - """Why `member`, a `consolidated_metadata` object, is not the envelope the core spec fixes: `kind` `"inline"`, `must_understand` false and an object at `metadata`, and nothing else. The entries of `metadata` are not checked. Each problem is located in the member.""" + """Why `member`, a `consolidated_metadata` object, is not the envelope the core spec fixes: `kind` `"inline"`, `must_understand` false and an object at `metadata`, and nothing else, though what another member holds must still be JSON. The entries of `metadata` are not checked. Each problem is located in the member.""" # Missing members are reported in the order the envelope declares them. problems: list[ValidationProblem] = [ ValidationProblem((key,), "missing required key", "missing_key") @@ -995,6 +996,11 @@ def _envelope_problems(member: Mapping[object, object]) -> list[ValidationProble if key not in member ] problems.extend(unexpected_keys(frozenset(_CONSOLIDATED_MEMBERS), member)) + # A member left out is still refined, as a closed TypedDict's checker + # refines it: no annotation says it may hold a number that is not finite. + for key, entry in member.items(): + if isinstance(key, str) and key not in _CONSOLIDATED_MEMBERS: + problems.extend(refine_json(entry, (key,))[1]) problems.extend(check_literal(member, "kind", "inline")) problems.extend(check_literal(member, "must_understand", False)) if "metadata" in member and not is_object(member["metadata"]): diff --git a/packages/zarr-metadata/tests/model/test_typed_document.py b/packages/zarr-metadata/tests/model/test_typed_document.py index 58177310e6..62745466fc 100644 --- a/packages/zarr-metadata/tests/model/test_typed_document.py +++ b/packages/zarr-metadata/tests/model/test_typed_document.py @@ -12,7 +12,12 @@ from zarr_metadata._common import UserJSONValue from zarr_metadata._json import JSON_DEPTH from zarr_metadata.definition import AcceptedDeclaration, RefusedDeclaration, resolve -from zarr_metadata.model import ZarrV3ArrayMetadata, read_array_metadata_v3 +from zarr_metadata.model import ( + ZarrV3ArrayMetadata, + read_array_metadata_v3, + read_consolidated_metadata_v3, + read_group_metadata_v3, +) from zarr_metadata.v3._common import ZarrV3CodecDeclaration from zarr_metadata.v3.definition import ( CORE_CONTEXT, @@ -149,6 +154,14 @@ def _array(**members: object) -> dict[str, object]: (("acme.mix", "scale"), "invalid_value"), }, ), + # A key the configuration does not declare is reported, and what it + # holds is still refined: no annotation says it may hold a number + # that is not finite. + ( + _array(**{"acme.note": {"note": 1, "must_understand": True, "x": math.nan}}), + _NOTE_CONTEXT, + {(("acme.note", "x"), "unknown_key"), (("acme.note", "x"), "invalid_value")}, + ), ], ids=[ "non-json-codec", @@ -158,6 +171,7 @@ def _array(**members: object) -> dict[str, object]: "claimed-nan", "user-data-where-annotated", "not-finite-elsewhere", + "not-finite-under-unknown-key", ], ) def test_every_problem_in_a_document_is_reported( @@ -212,3 +226,27 @@ def test_a_declaration_without_a_configuration_reads_up_to_the_last_level( ) assert problems == () assert isinstance(resolved, AcceptedDeclaration) + + +def test_error_a_consolidated_envelope_refines_a_member_it_leaves_out() -> None: + # Read alone or in its group, the envelope reports the same problems. + array = json.loads(json.dumps(ZarrV3ArrayMetadata.create_default(shape=(4,)).to_json())) + envelope = { + "kind": "inline", + "must_understand": False, + "metadata": {"x": array}, + "foo": math.nan, + } + group = { + "zarr_format": 3, + "node_type": "group", + "attributes": {}, + "consolidated_metadata": envelope, + } + expected = [(("foo",), "unknown_key"), (("foo",), "invalid_value")] + alone = read_consolidated_metadata_v3(envelope).problems + in_group = read_group_metadata_v3(group).problems + assert sorted((problem.loc, problem.kind) for problem in alone) == sorted(expected) + assert sorted((problem.loc, problem.kind) for problem in in_group) == sorted( + (("consolidated_metadata", *loc), kind) for loc, kind in expected + ) From fcc57952be558e6f964218662cafab25a5f3785a Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 11:57:11 +0100 Subject: [PATCH 11/27] fix(zarr-metadata): check a consolidated envelope with the checker the group uses `read_consolidated_metadata_v3` checked the envelope by hand, so it drifted from the group's extension field, which checks the same member by `ZarrV3ConsolidatedMetadataEnvelopeJSON`: it counted depth under an unexpected member one level short, ordered problems differently, and reported `kind: Infinity` as a wrong type. It now runs that checker, with the entries of `metadata` left out because each is read as a document, so both readers report the same problems in the same order. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../src/zarr_metadata/model/_group_v3.py | 35 +++--------- .../tests/model/test_typed_document.py | 56 +++++++++++++++---- 2 files changed, 53 insertions(+), 38 deletions(-) diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py index 33f7bee027..8133318241 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py @@ -29,7 +29,6 @@ not_an_object, outside_of, prefixed, - refine_json, refine_user_data, said, shown, @@ -39,6 +38,7 @@ ) from zarr_metadata._json import prefixed as _prefix from zarr_metadata._sentinel import UNSET +from zarr_metadata._typed_json import check from zarr_metadata.definition._context import disagreements, scoped from zarr_metadata.definition._definition import ( UnclaimedDeclaration, @@ -78,7 +78,6 @@ missing_keys, reading_of, unclaimed_declarations_of, - unexpected_keys, ) from zarr_metadata.v3._common import ( ZARR_V3_NODE_TYPE, @@ -94,6 +93,7 @@ from zarr_metadata.v3._hierarchy import hierarchy_problems, path_faults from zarr_metadata.v3.consolidated import ( ZARR_V3_CONSOLIDATED_METADATA_KEY, + ZarrV3ConsolidatedMetadataEnvelopeJSON, ZarrV3ConsolidatedMetadataJSON, ) from zarr_metadata.v3.group import ZARR_V3_GROUP_METADATA_STORE_KEY, ZarrV3GroupMetadataJSON @@ -979,33 +979,16 @@ def read_group_v3( return reading, GroupMembersV3(attributes, extra_fields, consolidated, document) -_CONSOLIDATED_MEMBERS: Final = ("kind", "must_understand", "metadata") -"""The members of an inline `consolidated_metadata`, in the order the convention declares them.""" - - _CONSOLIDATED_ENVELOPE: Final[dict[str, JSONValue]] = {"kind": "inline", "must_understand": False} """The fixed values the convention declares for the member.""" -def _envelope_problems(member: Mapping[object, object]) -> list[ValidationProblem]: - """Why `member`, a `consolidated_metadata` object, is not the envelope the core spec fixes: `kind` `"inline"`, `must_understand` false and an object at `metadata`, and nothing else, though what another member holds must still be JSON. The entries of `metadata` are not checked. Each problem is located in the member.""" - # Missing members are reported in the order the envelope declares them. - problems: list[ValidationProblem] = [ - ValidationProblem((key,), "missing required key", "missing_key") - for key in _CONSOLIDATED_MEMBERS - if key not in member - ] - problems.extend(unexpected_keys(frozenset(_CONSOLIDATED_MEMBERS), member)) - # A member left out is still refined, as a closed TypedDict's checker - # refines it: no annotation says it may hold a number that is not finite. - for key, entry in member.items(): - if isinstance(key, str) and key not in _CONSOLIDATED_MEMBERS: - problems.extend(refine_json(entry, (key,))[1]) - problems.extend(check_literal(member, "kind", "inline")) - problems.extend(check_literal(member, "must_understand", False)) - if "metadata" in member and not is_object(member["metadata"]): - problems.append(ValidationProblem(("metadata",), "expected an object", "invalid_type")) - return problems +def _envelope_problems(member: Mapping[object, object], at: Loc) -> tuple[ValidationProblem, ...]: + """Why `member`, a `consolidated_metadata` object at `at`, is not the envelope the core spec fixes, as the group's extension field checks it: by `ZarrV3ConsolidatedMetadataEnvelopeJSON`. The entries of `metadata` are left out, since each is read as a document. Each problem is located in the member.""" + entries = member.get("metadata") + envelope: Mapping[object, object] = {**member, "metadata": {}} if is_object(entries) else member + _, found = check(envelope, ZarrV3ConsolidatedMetadataEnvelopeJSON, at) + return within(found, at) def _read_node_model( @@ -1121,7 +1104,7 @@ def _read_consolidated_v3( with_input((ValidationProblem((), "expected an object", "invalid_type"),), value), ) env = value - problems = _envelope_problems(env) + problems = list(_envelope_problems(env, at)) readings: dict[str, ZarrV3NodeMetadataReading] = {} members: dict[str, ArrayMembersV3 | GroupMembersV3] = {} listings: dict[str, _Listing] = {} diff --git a/packages/zarr-metadata/tests/model/test_typed_document.py b/packages/zarr-metadata/tests/model/test_typed_document.py index 62745466fc..1e0c7ac90e 100644 --- a/packages/zarr-metadata/tests/model/test_typed_document.py +++ b/packages/zarr-metadata/tests/model/test_typed_document.py @@ -228,25 +228,57 @@ def test_a_declaration_without_a_configuration_reads_up_to_the_last_level( assert isinstance(resolved, AcceptedDeclaration) -def test_error_a_consolidated_envelope_refines_a_member_it_leaves_out() -> None: - # Read alone or in its group, the envelope reports the same problems. +@pytest.mark.parametrize( + ("extra", "expected"), + [ + ({"foo": math.nan}, [(("foo",), "unknown_key"), (("foo",), "invalid_value")]), + ( + {"foo": math.nan, "bar": math.inf}, + [ + (("foo",), "unknown_key"), + (("foo",), "invalid_value"), + (("bar",), "unknown_key"), + (("bar",), "invalid_value"), + ], + ), + ({"foo": _deep(JSON_DEPTH - 2)}, [(("foo",), "unknown_key")]), + ], + ids=["nan", "two-keys", "deepest"], +) +def test_error_a_consolidated_envelope_refines_a_member_it_leaves_out( + extra: dict[str, object], expected: list[tuple[Loc, str]] +) -> None: + # Read alone or in its group, the envelope reports the same problems, + # in the same order, and counts depth from the root of the group. array = json.loads(json.dumps(ZarrV3ArrayMetadata.create_default(shape=(4,)).to_json())) - envelope = { - "kind": "inline", - "must_understand": False, - "metadata": {"x": array}, - "foo": math.nan, - } + envelope = {"kind": "inline", "must_understand": False, "metadata": {"x": array}, **extra} group = { "zarr_format": 3, "node_type": "group", "attributes": {}, "consolidated_metadata": envelope, } - expected = [(("foo",), "unknown_key"), (("foo",), "invalid_value")] alone = read_consolidated_metadata_v3(envelope).problems in_group = read_group_metadata_v3(group).problems - assert sorted((problem.loc, problem.kind) for problem in alone) == sorted(expected) - assert sorted((problem.loc, problem.kind) for problem in in_group) == sorted( + assert [(problem.loc, problem.kind) for problem in alone] == expected + assert [(problem.loc, problem.kind) for problem in in_group] == [ (("consolidated_metadata", *loc), kind) for loc, kind in expected - ) + ] + + +def test_error_a_consolidated_envelope_counts_depth_from_the_group() -> None: + # The envelope is a group's member, so a member it leaves out reaches + # the last level one list sooner than it would at the root. + array = json.loads(json.dumps(ZarrV3ArrayMetadata.create_default(shape=(4,)).to_json())) + envelope = { + "kind": "inline", + "must_understand": False, + "metadata": {"x": array}, + "foo": _deep(JSON_DEPTH - 1), + } + problems = read_consolidated_metadata_v3(envelope).problems + assert [(problem.loc[:1], problem.kind) for problem in problems] == [ + (("foo",), "unknown_key"), + (("foo",), "invalid_value"), + ] + assert len(problems[1].loc) == JSON_DEPTH - 1 From aec16c1d57378bb0675751754f39f2acef365ca3 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 12:06:27 +0100 Subject: [PATCH 12/27] test(zarr-metadata): pin a non-finite consolidated kind as a value problem in both readers Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/tests/model/test_typed_document.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/zarr-metadata/tests/model/test_typed_document.py b/packages/zarr-metadata/tests/model/test_typed_document.py index 1e0c7ac90e..cb18f532d3 100644 --- a/packages/zarr-metadata/tests/model/test_typed_document.py +++ b/packages/zarr-metadata/tests/model/test_typed_document.py @@ -242,8 +242,9 @@ def test_a_declaration_without_a_configuration_reads_up_to_the_last_level( ], ), ({"foo": _deep(JSON_DEPTH - 2)}, [(("foo",), "unknown_key")]), + ({"kind": math.inf}, [(("kind",), "invalid_value")]), ], - ids=["nan", "two-keys", "deepest"], + ids=["nan", "two-keys", "deepest", "kind-not-finite"], ) def test_error_a_consolidated_envelope_refines_a_member_it_leaves_out( extra: dict[str, object], expected: list[tuple[Loc, str]] From a14f091a85bf3e80488bb19b5ba3791cd6bef850 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 12:09:08 +0100 Subject: [PATCH 13/27] docs(zarr-metadata): describe where a non-finite number may appear in the changelog entry Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/changes/493.feature.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/zarr-metadata/changes/493.feature.md b/packages/zarr-metadata/changes/493.feature.md index fa5f35e88c..b68c867e0d 100644 --- a/packages/zarr-metadata/changes/493.feature.md +++ b/packages/zarr-metadata/changes/493.feature.md @@ -1 +1 @@ -Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is now located at the element, such as `('shape', 1)`, rather than at the member, and nesting inside `shape` is counted from the root of the input, also in a consolidated listing. The annotations now say where a number that is not finite may appear: `attributes` and unclaimed extension fields are typed `UserJSONValue`, and the generated JSON Schema gives the documents' other keys that type. Some problem messages, and the order problems are reported in, have changed. +Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite may now appear only where an annotation says `UserJSONValue`: `attributes`, unclaimed extension fields, and those members of an extension field's configuration when its definition sets `finite=False`. `typed_json.check` follows the same annotations, so it accepts such numbers in `attributes`, and it returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. From 1aa86a88bcd1fb088c327d573bdfcb60b61a0ee0 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 12:52:55 +0100 Subject: [PATCH 14/27] refactor(zarr-metadata)!: make the annotation checker the only judge of what a v3 declaration may hold `ExtraFieldDefinition.finite` is removed: a configuration says where a number that is not finite may stand by typing that member `UserJSONValue`. A v3 declaration is no longer refined strictly before it is read, a pass that stopped at the first value that was not JSON and so hid every other problem. Its kind refines it as user data only to build the JSON a reading holds (`UNSET` when it is not JSON). Then its envelope check, its definition's configuration check, or the kind's check of an unread configuration (`_unread`) each decide by annotation, on the declaration as written when it is not JSON. The same holds for nested declarations and for `read_configuration`. The envelope check passes the configuration on once it is an object, so its keys are checked once. An extension field's configuration keeps keys that are not strings, so its checker reports them. v2 kinds, whose envelopes are checked by hand, still refine strictly first. A refused declaration now holds what was written when it is JSON with any number, and a NaN in a nested codec refuses that codec, not the one that holds it. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/changes/493.feature.md | 2 +- .../zarr-metadata/docs/validation-rules.md | 5 +- .../src/zarr_metadata/definition/__init__.py | 5 +- .../zarr_metadata/definition/_definition.py | 159 +++++++++++------- .../src/zarr_metadata/definition/_envelope.py | 15 +- .../src/zarr_metadata/model/_array_v3.py | 5 +- .../src/zarr_metadata/v2/_definition.py | 22 ++- .../src/zarr_metadata/v3/_definition.py | 63 ++++--- .../src/zarr_metadata/v3/consolidated.py | 3 +- .../zarr-metadata/tests/model/test_array.py | 18 +- .../tests/model/test_extension_points.py | 11 +- .../tests/model/test_extra_fields.py | 18 +- .../tests/model/test_store_json.py | 6 +- .../tests/model/test_typed_document.py | 49 ++++-- .../tests/v3/test_definitions.py | 33 +++- 15 files changed, 254 insertions(+), 160 deletions(-) diff --git a/packages/zarr-metadata/changes/493.feature.md b/packages/zarr-metadata/changes/493.feature.md index b68c867e0d..7cecef31e8 100644 --- a/packages/zarr-metadata/changes/493.feature.md +++ b/packages/zarr-metadata/changes/493.feature.md @@ -1 +1 @@ -Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite may now appear only where an annotation says `UserJSONValue`: `attributes`, unclaimed extension fields, and those members of an extension field's configuration when its definition sets `finite=False`. `typed_json.check` follows the same annotations, so it accepts such numbers in `attributes`, and it returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. +Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite may appear only where an annotation says `UserJSONValue`, such as `attributes` and unclaimed extension fields; `ExtraFieldDefinition`'s `finite` is removed, and a configuration says where with that annotation. A value that is not JSON no longer stops a declaration from being read, so every other problem in it is reported. `typed_json.check` follows the same annotations, and returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. diff --git a/packages/zarr-metadata/docs/validation-rules.md b/packages/zarr-metadata/docs/validation-rules.md index 5a0b194c21..a8e1c133ab 100644 --- a/packages/zarr-metadata/docs/validation-rules.md +++ b/packages/zarr-metadata/docs/validation-rules.md @@ -8,8 +8,9 @@ context. For example: ([`zarr_format`](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#zarr-format) and [`node_type`](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#node-type)), -- finite JSON numbers, except in `attributes` and in members that nothing - in the context reads, +- finite JSON numbers, except in `attributes`, in members that nothing + in the context reads, and where an extension field's configuration + says `UserJSONValue`, - non-negative [dimensions](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#array-metadata-shape), - one diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py index 6cb5066d22..00aa1201cd 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py @@ -273,9 +273,8 @@ def acme_lz4_rules( called for a codec of its kind (chunk rules or pipelines of a bytes -> bytes codec, which receives bytes, or a `transition` of a codec that outputs bytes); a data type named the way raw bits of one size are -written; an extra field named after a member the spec defines, whose -`finite` is not a boolean, or whose configuration does not declare -`must_understand`. Building a definition files it nowhere: only a scope +written; an extra field named after a member the spec defines, or whose +configuration does not declare `must_understand`. Building a definition files it nowhere: only a scope built from it does. """ diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index 8ecee5e300..3d381d2f98 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -292,9 +292,26 @@ def _unclaimed_json( @classmethod def _refined( cls, data: object, loc: Loc, definition: Definition[Any] | None - ) -> tuple[JSONValue | None, Problems]: - """`data`, a declaration of this kind at `loc`, refined to JSON before it is read, with every reason it is not JSON. `definition` is the definition that claims the declaration, if any. By default every number must be finite, as RFC 8259 requires.""" - return refine_json(data, loc) + ) -> tuple[JSONValue | UNSET, Problems]: + """`data`, a declaration of this kind at `loc`, as the JSON a reading of it holds (`UNSET` when it is not JSON), and every problem that keeps a definition from reading it at all. `definition` is the definition that claims the declaration, if any. + + By default nothing keeps a declaration from being read, and it is + refined as user data, so a number need not be finite. What it may + hold is decided by the checks that read it, each by its annotation: + its envelope's, then its definition's configuration, or `_unread` + when nothing claims it. Each runs on the declaration as written + when it is not JSON, so every problem is reported. + """ + refined, found = refine_user_data(data, loc) + return (UNSET if len(found) != 0 else refined), () + + @classmethod + def _unread(cls, data: object, json: JSONValue | UNSET, loc: Loc) -> Problems: + """Every problem of `data`, a declaration of this kind at `loc` that no definition reads, beyond its envelope's: its configuration must be JSON, every number finite, as `JSONValue` says. `json` is the declaration as `_refined` refined it.""" + given = cls._named_configuration(data)[1] + if given is None: + return () + return _in_document(cls, loc, True, refine_json(given, cls._in_configuration(loc, ()))[1]) @classmethod def _undeclared_parts(cls, family: str, name: str, keys: Sequence[str]) -> str: @@ -374,10 +391,6 @@ def _refusal(self) -> str | None: """A description of what is wrong with the attributes a kind adds; None if nothing is wrong, or if the kind adds no attributes.""" return None - def _finite_numbers(self) -> bool: - """Whether every number in a configuration this definition reads must be finite, as RFC 8259 requires. A kind whose configuration may hold user data overrides this.""" - return True - @property def requires_configuration(self) -> bool: """Whether a document must include a configuration, meaning the TypedDict has a required key.""" @@ -390,9 +403,7 @@ def _check_configuration(self, value: object, loc: Loc = ()) -> tuple[C | None, method also checks the envelope of each declaration that a member holds. """ - configuration, problems = _configuration_checked( - value, self.configuration, loc, finite=self._finite_numbers() - ) + configuration, problems = _configuration_checked(value, self.configuration, loc) return configuration, with_input(problems, value, loc) def read_configuration(self, value: object, loc: Loc = ()) -> tuple[C | None, Problems]: @@ -601,25 +612,25 @@ class _NestedDeclaration: loc: Loc kind: type[Definition[Any]] - json: JSONValue - """The declaration refined as JSON; None when it is not JSON.""" + json: JSONValue | UNSET + """The declaration as JSON, as its kind refines it (`_refined`); `UNSET` when it is not JSON.""" alias: TypeAliasType """Whether the member that holds it accepts only codecs of static size.""" written: object """The declaration as written.""" problems: Problems - """Every reason the declaration is not JSON, located in the input.""" + """Every problem that keeps a definition from reading the declaration at all, as its kind finds them (`_refined`), located in the input.""" class _DeclarationParser: - """The parser of a member that holds a declaration: it refines the declaration where it sits and passes it on, with every reason it is not JSON. The declaration itself is never a problem of the member's type: whoever reads it (`check` without a scope, `resolve` with one) checks the envelope and maps the name to a definition, and refuses one that is not JSON.""" + """The parser of a member that holds a declaration: it refines the declaration where it sits, as its kind refines declarations, and passes it on. The declaration itself is never a problem of the member's type: whoever reads it (`check` without a scope, `resolve` with one) checks it and reports what it finds.""" def __init__(self, kind: type[Definition[Any]], alias: TypeAliasType) -> None: self.kind = kind self.alias = alias def __call__(self, value: object, loc: Loc) -> Parsed: - refined, found = refine_json(value, loc) + refined, found = self.kind._refined(value, loc, None) return _NestedDeclaration(loc, self.kind, refined, self.alias, value, found), () @@ -768,14 +779,14 @@ def _collect(value: object, nested: list[_NestedDeclaration]) -> None: def _as_written(declaration: _NestedDeclaration) -> JSONValue: - """A nested declaration restored as it was written.""" - return declaration.json + """A nested declaration restored as it was written: None when it is not JSON, which reading it reports.""" + return None if declaration.json is UNSET else declaration.json def _envelope_keys_only(declaration: _NestedDeclaration) -> JSONValue: """A nested declaration restored as it was written, except for the members its envelope TypedDict does not declare. Those are reported and left out, in the same way the checker leaves out a key that a closed TypedDict does not declare.""" if not isinstance(declaration.json, Mapping): - return declaration.json + return _as_written(declaration) envelope = cast("Mapping[str, JSONValue]", declaration.json) return {key: value for key, value in envelope.items() if key in ENVELOPE_KEYS} @@ -870,11 +881,24 @@ def _located(prefix: Loc, problems: Iterable[ValidationProblem]) -> Problems: return tuple(dataclasses.replace(each, loc=(*prefix, *each.loc)) for each in found) +def _as_read(declaration: _NestedDeclaration) -> object: + """A nested declaration as it is read: its JSON, or as written when it is not JSON.""" + return declaration.written if declaration.json is UNSET else declaration.json + + def _envelope(declaration: _NestedDeclaration) -> Problems: - """The problems with a nested declaration's envelope, located at the declaration; for a declaration that is not JSON, every reason it is not.""" + """The problems with a nested declaration's envelope, located at the declaration; for a declaration its kind does not read at all, the problems that keep it from being read.""" if len(declaration.problems) != 0: return declaration.problems - return _located(declaration.loc, declaration.kind._envelope_problems(declaration.json)) + return _located(declaration.loc, declaration.kind._envelope_problems(_as_read(declaration))) + + +def _unread_problems(declaration: _NestedDeclaration) -> Problems: + """Every problem with a nested declaration that no scope reads: its envelope's, and its configuration's as its kind checks an unread one (`_unread`).""" + if len(declaration.problems) != 0: + return declaration.problems + unread = declaration.kind._unread(_as_read(declaration), declaration.json, declaration.loc) + return (*_envelope(declaration), *unread) def _moved(declaration: _NestedDeclaration, loc: Loc) -> _NestedDeclaration: @@ -887,7 +911,7 @@ def _moved(declaration: _NestedDeclaration, loc: Loc) -> _NestedDeclaration: def _configuration_checked( - value: object, shape: type[T], loc: Loc = (), *, finite: bool = True + value: object, shape: type[T], loc: Loc = () ) -> tuple[T | None, Problems]: """Check `value` as `shape`, as `typed_json.check` does, and check the envelope of each nested declaration. @@ -897,15 +921,18 @@ def _configuration_checked( is a problem of the configuration, and no value is returned. An extra member is an unknown key: it is reported and left out, and the value is still returned. This matches how the checker reports and leaves out a - key that a closed TypedDict does not declare. A number that is not - finite is a problem, except where the TypedDict says `UserJSONValue` - and `finite` is false, for a configuration that holds user data. + key that a closed TypedDict does not declare. The check refines `value` + as it goes, so a part that is not JSON is reported where it sits, + beside every other problem, and a number that is not finite is a + problem except where the TypedDict says `UserJSONValue`. No scope reads + a nested declaration here, so its configuration is checked as an unread + one (`_unread`). """ - refined, problems = (refine_json if finite else refine_user_data)(value, loc) - if len(problems) != 0: - return None, problems - typed, found, nested = _typed(shape, refined, loc) - problems = (*found, *(problem for declaration in nested for problem in _envelope(declaration))) + typed, found, nested = _typed(shape, value, loc) + problems = ( + *found, + *(problem for declaration in nested for problem in _unread_problems(declaration)), + ) if not _usable(problems): return None, problems return cast("T", _put_back(typed, _envelope_keys_only, nested)), problems @@ -981,8 +1008,8 @@ def read_found( ) -> tuple[ResolvedDeclaration[Any], Problems]: """Read `declaration`, which `typed_document` found in a document at `at`, in `context`, as `resolve` reads it, and check that the member's alias admits the definition that read it. The problems are located in the document. - `typed_document` refined the declaration as JSON, which is how its - kind refines declarations, so it is read without being refined again. + `typed_document` refined the declaration as its kind refines + declarations, so it is read without being refined again. """ resolved, found = resolve_refined( declaration.written, @@ -1193,7 +1220,7 @@ class RefusedDeclaration(Generic[D]): """A declaration that could not be read: it is not a declaration at all, not JSON, or rejected by the definition that claims its name. Its problems explain why.""" json: JSONValue | UNSET - """The declaration as written, refined (arrays as tuples). `UNSET` when it is not JSON, which no document can contain.""" + """The declaration as written, refined as user data (arrays as tuples, any number). `UNSET` when it is not JSON even so, which no document can contain.""" name: str | None """The name the declaration is written with; None when it has no name.""" read_as: type[Definition[Any]] @@ -1703,18 +1730,20 @@ def described(context: object) -> str: def resolve_refined( data: object, - refined: JSONValue | None, + refined: JSONValue | UNSET, problems: Problems, kind: type[D], context: Context, loc: Loc = (), ) -> tuple[ResolvedDeclaration[D], Problems]: - """`resolve` for `data` that the caller has already refined. `refined` and `problems` are the result of `refine_json(data, loc)`. + """`resolve` for `data` that the caller has already refined, as the kind's `_refined` does: `refined` is its JSON (`UNSET` when it is not JSON), and `problems` every problem that keeps a definition from reading it at all. This is for a reader that refines a document's members once and keeps the result (the document a model holds is built from it), instead of - refining each declaration again here. `problems` shows whether `data` is - JSON. If it contains any problems, `refined` is not used. + refining each declaration again here. When `problems` holds any, the + declaration is refused with them and `refined` is not used. Otherwise it + is read: as JSON when `refined` holds it, else as written, so that each + check reports what it finds and the declaration is refused. """ asked = as_kind(kind) _check_format(asked, context) @@ -1729,51 +1758,58 @@ def resolve_refined( refused = RefusedDeclaration(json=UNSET, name=name, read_as=asked, definition=claimant) found = problems if bad is None else (bad, *problems) return cast("ResolvedDeclaration[D]", refused), with_input(found, data, loc) - resolved, found = _resolve_declaration(refined, asked, context, loc) + resolved, found = _resolve_declaration(data, refined, asked, context, loc) return cast("ResolvedDeclaration[D]", resolved), with_input(found, data, loc) def _resolve_declaration( - data: JSONValue, kind: type[Definition[Any]], context: Context, loc: Loc + data: object, json: JSONValue | UNSET, kind: type[Definition[Any]], context: Context, loc: Loc ) -> tuple[ResolvedDeclaration[Definition[Any]], Problems]: - """Check the envelope of a refined declaration, then read the declaration. + """Check the envelope of a declaration, then read the declaration: `json` is its JSON, or `UNSET` when it is not JSON, and it is then checked as written, `data`. The result of the reading depends only on the configuration. An extra member or a `must_understand` of `false` does not affect the configuration, so it is reported alongside the declaration that was read, and later layers can still check that declaration. """ - envelope = _located(loc, kind._envelope_problems(data)) - resolved, found = _read(data, kind, context, loc) + read = data if json is UNSET else json + envelope = _located(loc, kind._envelope_problems(read)) + resolved, found = _read(read, json, kind, context, loc) return resolved, (*envelope, *found) def _read( - data: JSONValue, kind: type[Definition[Any]], context: Context, loc: Loc + data: object, json: JSONValue | UNSET, kind: type[Definition[Any]], context: Context, loc: Loc ) -> tuple[ResolvedDeclaration[Definition[Any]], Problems]: + """Read `data`, a declaration of `kind` at `loc` whose envelope its caller checks: its JSON, `json`, or as written when that is `UNSET`. A declaration that is not JSON is refused, with what its checks find.""" name, given, malformed = kind._named_configuration(data) if name is None: - return RefusedDeclaration(json=data, name=None, read_as=kind), () + return RefusedDeclaration(json=json, name=None, read_as=kind), () if not kind._well_named(name): # The envelope check that every reader runs first reports this. No - # definition is looked up for the name. - return RefusedDeclaration(json=data, name=name, read_as=kind), () + # definition is looked up for the name, so its configuration is + # checked as an unread one. + unread = kind._unread(data, json, loc) + return RefusedDeclaration(json=json, name=name, read_as=kind), unread definition = context.claimant(kind, name) if len(malformed) != 0: # The configuration is not an object, which the envelope problems # report. The name still determines which definition claims the # declaration. - return RefusedDeclaration(json=data, name=name, read_as=kind, definition=definition), () + return RefusedDeclaration(json=json, name=name, read_as=kind, definition=definition), () if definition is None: - return UnclaimedDeclaration(json=data, name=name, read_as=kind), () + unread = kind._unread(data, json, loc) + if json is UNSET or len(unread) != 0: + return RefusedDeclaration(json=json, name=name, read_as=kind), unread + return UnclaimedDeclaration(json=json, name=name, read_as=kind), () _, carried = kind._filed_under(name) if carried is not None: - return _read_carried(data, name, kind, definition, given, carried, loc) + return _read_carried(data, json, name, kind, definition, given, carried, loc) at = kind._in_configuration(loc, ()) if given is None and definition.requires_configuration: missing = problem(at, f"{name!r} requires a configuration", "missing_key") return RefusedDeclaration( - json=data, name=name, read_as=kind, definition=definition + json=json, name=name, read_as=kind, definition=definition ), missing typed, found, nested = _given(definition.configuration, given, at) # Read the nested declarations first, each one stack frame deeper, so the @@ -1795,7 +1831,9 @@ def _read( ) else: inside.extend(_envelope(placed)) - inner, found_inside = _read(placed.json, placed.kind, context, placed.loc) + inner, found_inside = _read( + _as_read(placed), placed.json, placed.kind, context, placed.loc + ) within[place] = inner written[declaration.loc] = cast("JSONValue", document_json(inner)) inside.extend(found_inside) @@ -1819,13 +1857,13 @@ def _read( ruled(definition, lambda: definition.rules(read_only(configuration), within), at) ) placed = _in_document(kind, loc, given is not None, own) - if configuration is None or not _usable(placed): + if configuration is None or json is UNSET or not _usable(placed): refused = RefusedDeclaration( - json=data, name=name, read_as=kind, definition=definition, nested=within + json=json, name=name, read_as=kind, definition=definition, nested=within ) return refused, (*placed, *inside) read = AcceptedDeclaration( - json=data, name=name, definition=definition, configuration=configuration, nested=within + json=json, name=name, definition=definition, configuration=configuration, nested=within ) return read, (*placed, *inside) @@ -1886,7 +1924,8 @@ def _given( def _read_carried( - data: JSONValue, + data: object, + json: JSONValue | UNSET, name: str, kind: type[Definition[Any]], definition: Definition[Any], @@ -1937,11 +1976,17 @@ def _read_carried( message = kind._undeclared_parts(definition.name, name, undeclared) problems = (*problems, ValidationProblem(loc, message, "invalid_value")) # Any problem with the encoded configuration refuses the declaration. - if configuration is None or not _usable(beside) or len(judged) != 0 or len(undeclared) != 0: - refused = RefusedDeclaration(json=data, name=name, read_as=kind, definition=definition) + if ( + json is UNSET + or configuration is None + or not _usable(beside) + or len(judged) != 0 + or len(undeclared) != 0 + ): + refused = RefusedDeclaration(json=json, name=name, read_as=kind, definition=definition) return refused, problems return AcceptedDeclaration( - json=data, name=name, definition=definition, configuration=configuration + json=json, name=name, definition=definition, configuration=configuration ), problems diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py b/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py index 842fb83f6b..8af23673d0 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py @@ -6,11 +6,12 @@ import functools import re +from collections.abc import Mapping from typing import Final from zarr_metadata._common import JSONValue, ZarrV3NamedConfigJSON from zarr_metadata._json import ValidationProblem, is_object, shown -from zarr_metadata._typed_json import Loc, Parsed, Parser, parser +from zarr_metadata._typed_json import Loc, Parsed, Parser, parser, problem ENVELOPE_KEYS: frozenset[str] = frozenset({"name", "configuration", "must_understand"}) """The keys a declaration's envelope declares. Any other key is an unknown key.""" @@ -61,14 +62,16 @@ def name_problem(name: str, at: tuple[str | int, ...]) -> ValidationProblem | No def _opaque(annotation: object) -> Parser | None: - """The leaf the envelope's checker uses: a value annotated `JSONValue` inside the envelope (a configuration member) is passed on unread. The definition that reads the configuration checks it, so the envelope check walks only the envelope.""" - if annotation is JSONValue: - return _passed_on + """The leaf the envelope's checker uses: the configuration, once found to be an object, is passed on unread. Whoever reads the configuration checks its keys and values (its definition, or the kind's check of an unread one), so the envelope check walks only the envelope and reports nothing twice.""" + if annotation == Mapping[str, JSONValue]: + return _an_object return None -def _passed_on(value: object, loc: Loc) -> Parsed: - return value, () +def _an_object(value: object, loc: Loc) -> Parsed: + if is_object(value): + return value, () + return value, problem(loc, f"expected an object, got {shown(value)}") _ENVELOPE: Final[Parser] = parser(str | ZarrV3NamedConfigJSON, _opaque) diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py index 6d6c7e7547..d2b7d9ec33 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py @@ -291,8 +291,9 @@ def read_extra_fields_v3( Returns three values: each member that is JSON, refined; each member as the scope read it, by key; and every problem, located in the document. A member that a definition in `context` claims is read by that - definition, and must be an object whose numbers are finite, unless the - definition reads user data. Any other member is not read: it is an + definition: it must be an object, which may hold a number that is not + finite only where the definition's configuration says `UserJSONValue`. + Any other member is not read: it is an `UnclaimedDeclaration`, and, like attributes, need only be JSON as Python's `json` module reads it. """ diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v2/_definition.py index ebe6fc1b04..4f661edfee 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/_definition.py @@ -21,11 +21,12 @@ import re from dataclasses import dataclass -from typing import TYPE_CHECKING, ClassVar, Final, cast +from typing import TYPE_CHECKING, Any, ClassVar, Final, cast from typing_extensions import TypeAliasType -from zarr_metadata._json import ValidationProblem, is_object, said, shown +from zarr_metadata._json import ValidationProblem, is_object, refine_json, said, shown +from zarr_metadata._sentinel import UNSET from zarr_metadata.definition._definition import ( C, Definition, @@ -208,6 +209,15 @@ def _named_configuration( return STRUCT_NAME, {_RECORDS: cast("JSONValue", value)}, () return None, None, () + @classmethod + def _refined( + cls, data: object, loc: Loc, definition: Definition[Any] | None + ) -> tuple[JSONValue | UNSET, Problems]: + # A v2 envelope is checked on JSON, so a declaration that is not + # JSON is not read. + refined, found = refine_json(data, loc) + return (UNSET if len(found) != 0 else refined), found + @classmethod def _envelope_problems(cls, value: object) -> Problems: if isinstance(value, str): @@ -285,6 +295,14 @@ def _named_configuration( (), ) + @classmethod + def _refined( + cls, data: object, loc: Loc, definition: Definition[Any] | None + ) -> tuple[JSONValue | UNSET, Problems]: + # As for a v2 data type: the envelope is checked on JSON. + refined, found = refine_json(data, loc) + return (UNSET if len(found) != 0 else refined), found + @classmethod def _envelope_problems(cls, value: object) -> Problems: if not is_object(value): diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py index fadaedf6ce..6085b75bef 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py @@ -520,13 +520,11 @@ class ExtraFieldDefinition(Definition[C]): lists it in `must_understand_fields` unless it says `"must_understand": false`. - `finite` says whether every number in the member must be finite, as - RFC 8259 JSON requires. A member that holds user data sets it to - False: consolidated metadata holds node documents, whose attributes - may hold `NaN`, `Infinity` and `-Infinity`. Even then, such a number - may stand only where the configuration's annotation is - `UserJSONValue`, as a node's attributes are. A member that nothing - claims is not read, so like attributes it may hold any number. + A number that is not finite may stand only where the configuration's + annotation is `UserJSONValue`, as a node's attributes are: consolidated + metadata holds node documents, whose attributes may hold `NaN`, + `Infinity` and `-Infinity`. A member that nothing claims is not read, + so like attributes it may hold any number. The spec lets every extension field carry `"must_understand": false`, which tells a reader that does not understand the member that it may @@ -536,19 +534,10 @@ class ExtraFieldDefinition(Definition[C]): definition named after one is refused too. """ - finite: bool = True - """Whether every number in the member must be finite, even where the configuration says `UserJSONValue`.""" - spec_members: ClassVar[frozenset[str]] = frozenset() """The members the spec defines in a document this kind reads extra fields of, which are never extra fields.""" - def _finite_numbers(self) -> bool: - return self.finite - def _refusal(self) -> str | None: - finite = cast("object", self.finite) - if not isinstance(finite, bool): - return f"{self.name!r}: finite is a boolean, got {finite!r}" if not is_typeddict(self.configuration): return None try: @@ -582,7 +571,7 @@ def _named_configuration( ) -> tuple[str | None, Mapping[str, object] | None, Problems]: # A member whose value is not an object has no configuration. Only # a definition that claims the member reads it, and `_refined` - # refuses such a value then. + # keeps it from being read then. if not is_object(value) or len(value) != 1: return None, None, () ((name, configuration),) = value.items() @@ -590,7 +579,9 @@ def _named_configuration( return None, None, () if not is_object(configuration): return name, None, () - return name, {key: item for key, item in configuration.items() if isinstance(key, str)}, () + # Passed on as written, so the configuration's checker reports a key + # that is not a string, as for any declaration. + return name, cast("Mapping[str, object]", configuration), () @classmethod def _envelope_problems(cls, value: object) -> Problems: @@ -607,23 +598,31 @@ def _envelope_problems(cls, value: object) -> Problems: @classmethod def _refined( cls, data: object, loc: Loc, definition: Definition[Any] | None - ) -> tuple[JSONValue | None, Problems]: - # The member's value is at the member's location, `loc`. A member - # nothing claims is not read, so like attributes it is user data. - # A claimed member is user data when its definition says so, and - # its value must be an object. + ) -> tuple[JSONValue | UNSET, Problems]: + # The member's value is at the member's location, `loc`, and is + # refined as user data: the checks that read it decide what it may + # hold. A claimed member's value must be an object, or no + # definition can read it. name = cls._named_configuration(data)[0] if name is None or not is_object(data): - return refine_json(data, loc) + refined, found = refine_user_data(data, loc) + return (UNSET if len(found) != 0 else refined), () if definition is not None and not is_object(data[name]): - return None, (ValidationProblem(loc, "expected an object", "invalid_type"),) - refine = ( - refine_json - if isinstance(definition, ExtraFieldDefinition) and definition.finite - else refine_user_data - ) - value, problems = refine(data[name], loc) - return (None if len(problems) != 0 else {name: value}), problems + return UNSET, (ValidationProblem(loc, "expected an object", "invalid_type"),) + value, found = refine_user_data(data[name], loc) + return (UNSET if len(found) != 0 else {name: value}), () + + @classmethod + def _unread(cls, data: object, json: JSONValue | UNSET, loc: Loc) -> Problems: + # A member nothing claims is user data, like attributes: it need + # only be JSON, with any number, which `_refined` found it is + # unless `json` is `UNSET`. + if json is not UNSET: + return () + name = cls._named_configuration(data)[0] + if name is None or not is_object(data): + return () + return refine_user_data(data[name], loc)[1] @classmethod def _envelope_json(cls, name: str, configuration: Mapping[str, JSONValue]) -> JSONValue: diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py b/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py index 4170a8d454..196f549e46 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py @@ -26,10 +26,9 @@ GroupExtraFieldDefinition( name=ZARR_V3_CONSOLIDATED_METADATA_KEY, configuration=ZarrV3ConsolidatedMetadataEnvelopeJSON, - finite=False, ) ) -"""A group's `consolidated_metadata` member, read as the envelope the core spec fixes. The documents it lists are not read: they may hold the non-finite numbers that node attributes may, and `ZarrV3ConsolidatedMetadata` reads them.""" +"""A group's `consolidated_metadata` member, read as the envelope the core spec fixes. The documents it lists are not read: its configuration types them as `UserJSONValue`, since they may hold the non-finite numbers that node attributes may, and `ZarrV3ConsolidatedMetadata` reads them.""" __all__ = [ diff --git a/packages/zarr-metadata/tests/model/test_array.py b/packages/zarr-metadata/tests/model/test_array.py index 875a1770aa..ad8cb99128 100644 --- a/packages/zarr-metadata/tests/model/test_array.py +++ b/packages/zarr-metadata/tests/model/test_array.py @@ -2721,12 +2721,10 @@ def test_a_problem_shows_an_integer_too_long_to_write_by_its_size( "holds here, as sys.get_int_max_str_digits bounds it" ), ) - (problem,) = resolve( - {"name": "gzip", 10**5000: 1}, CodecDefinition, CORE_AND_EXTENSIONS_CONTEXT - )[1] - assert problem.message == ( - f"non-string key an integer of {(10**5000).bit_length()} bits in JSON object" - ) + problem = resolve({"name": "gzip", 10**5000: 1}, CodecDefinition, CORE_AND_EXTENSIONS_CONTEXT)[ + 1 + ][0] + assert problem.message == f"non-string key an integer of {(10**5000).bit_length()} bits" # When such an integer is inside a container (JSON or not) or a key, the # message says the interpreter will not write the value. for held in ([10**5000], [10**5000, object()]): @@ -2735,12 +2733,10 @@ def test_a_problem_shows_an_integer_too_long_to_write_by_its_size( assert ( problem.message == "expected 2, got a value of type list the interpreter will not write" ) - (problem,) = resolve( + problem = resolve( {"name": "gzip", (10**5000,): 1}, CodecDefinition, CORE_AND_EXTENSIONS_CONTEXT - )[1] - assert problem.message == ( - "non-string key a value of type tuple the interpreter will not write in JSON object" - ) + )[1][0] + assert problem.message == "non-string key a value of type tuple the interpreter will not write" # The same applies to a value that `refine_json` reports as not JSON at # all: a set holding such an integer. document = {**ZarrV3ArrayMetadata.create_default().to_json(), "attributes": {"a": {10**5000}}} diff --git a/packages/zarr-metadata/tests/model/test_extension_points.py b/packages/zarr-metadata/tests/model/test_extension_points.py index e7c9fecc98..fc2c871c9a 100644 --- a/packages/zarr-metadata/tests/model/test_extension_points.py +++ b/packages/zarr-metadata/tests/model/test_extension_points.py @@ -196,9 +196,9 @@ def test_error_an_envelope_is_judged_once() -> None: ] == [(("codecs", 1, "must_understand"), "invalid_value")] -def test_error_a_declaration_that_is_not_json_is_not_read() -> None: - # The JSON check runs first. The NaN is reported, and the configuration - # next to it is not read. +def test_error_a_declaration_that_is_not_json_is_still_read() -> None: + # The NaN is reported where it sits, and the configuration next to it is + # still read, so its problem is reported too. document = _document( codecs=[ BYTES, @@ -207,4 +207,7 @@ def test_error_a_declaration_that_is_not_json_is_not_read() -> None: ) assert [ (problem.loc, problem.kind) for problem in read_array_metadata_v3(document).problems - ] == [(("codecs", 1, "must_understand"), "invalid_value")] + ] == [ + (("codecs", 1, "must_understand"), "invalid_value"), + (("codecs", 1, "configuration", "level"), "invalid_value"), + ] diff --git a/packages/zarr-metadata/tests/model/test_extra_fields.py b/packages/zarr-metadata/tests/model/test_extra_fields.py index db2729a2e4..5c30c0bad5 100644 --- a/packages/zarr-metadata/tests/model/test_extra_fields.py +++ b/packages/zarr-metadata/tests/model/test_extra_fields.py @@ -21,7 +21,7 @@ from zarr_metadata.json_schema import declaration_json_schema_v3 from zarr_metadata.model import ZarrV3ArrayMetadata, ZarrV3GroupMetadata from zarr_metadata.problems import MetadataValidationError -from zarr_metadata.typed_json import UserJSONValue +from zarr_metadata.typed_json import JSONValue from zarr_metadata.v3.definition import ( CORE_CONTEXT, ArrayExtraFieldDefinition, @@ -42,9 +42,9 @@ class AcmeTilingConfiguration(TypedDict, closed=True): class AcmeNoteConfiguration(TypedDict, closed=True): - """The value of an `acme.note` member: any JSON, and the waiver.""" + """The value of an `acme.note` member: any JSON, every number finite, and the waiver.""" - note: UserJSONValue + note: JSONValue must_understand: NotRequired[bool] @@ -197,7 +197,7 @@ def test_error_a_claimed_extra_field_with_a_bad_configuration() -> None: def test_error_a_non_finite_number_in_an_extra_field_that_holds_no_user_data() -> None: - """Every number in a claimed extra field must be finite unless its definition reads user data, as `CONSOLIDATED_METADATA_EXTRA_FIELD` does for the attributes of the documents it lists.""" + """A number in a claimed extra field must be finite unless its configuration says `UserJSONValue` there, as `CONSOLIDATED_METADATA_EXTRA_FIELD`'s does for the documents it lists.""" with pytest.raises(MetadataValidationError) as raised: ZarrV3ArrayMetadata({**ARRAY, "acme.note": {"note": [math.nan]}}, context=CONTEXT) assert [(p.loc, p.kind) for p in raised.value.problems] == [ @@ -362,16 +362,6 @@ def test_error_an_extra_field_configuration_that_refuses_the_waiver(configuratio ArrayExtraFieldDefinition(name="acme.bad", configuration=configuration) -def test_error_finite_is_a_boolean() -> None: - """`finite` decides whether a member may hold non-finite numbers, so it must be a boolean: anything else is refused when the definition is built.""" - with pytest.raises(TypeError, match="finite"): - ArrayExtraFieldDefinition( - name="acme.tiling", - configuration=AcmeTilingConfiguration, - finite=0, # pyright: ignore[reportArgumentType] - ) - - def test_error_an_extra_field_of_a_group_is_not_an_extra_field_of_an_array() -> None: """The slots of a scope hold extra fields by node type, so a group's extra field given in the array slot is refused, as any definition of another kind is.""" tiling = GroupExtraFieldDefinition(name="acme.tiling", configuration=AcmeTilingConfiguration) diff --git a/packages/zarr-metadata/tests/model/test_store_json.py b/packages/zarr-metadata/tests/model/test_store_json.py index 5a8d135e41..7507a24bae 100644 --- a/packages/zarr-metadata/tests/model/test_store_json.py +++ b/packages/zarr-metadata/tests/model/test_store_json.py @@ -252,12 +252,10 @@ def test_a_sequence_is_written_as_an_array() -> None: "zarr.json", { **_ARRAY, - "codecs": [ - {"name": "bytes", "configuration": {"endian": "little", "scale": math.inf}} - ], + "codecs": [{"name": "bytes", "configuration": {"endian": math.inf}}], }, ), - ("codecs", 0, "configuration", "scale"), + ("codecs", 0, "configuration", "endian"), ), # A group does not read the documents its consolidated metadata lists; # reading them finds the number. diff --git a/packages/zarr-metadata/tests/model/test_typed_document.py b/packages/zarr-metadata/tests/model/test_typed_document.py index cb18f532d3..13199da2b2 100644 --- a/packages/zarr-metadata/tests/model/test_typed_document.py +++ b/packages/zarr-metadata/tests/model/test_typed_document.py @@ -55,8 +55,8 @@ class _Mix(TypedDict, closed=True): _NOTE_CONTEXT = CORE_CONTEXT.union( ZarrV3Context( array_extra_fields=[ - ArrayExtraFieldDefinition(name="acme.note", configuration=_Note, finite=False), - ArrayExtraFieldDefinition(name="acme.mix", configuration=_Mix, finite=False), + ArrayExtraFieldDefinition(name="acme.note", configuration=_Note), + ArrayExtraFieldDefinition(name="acme.mix", configuration=_Mix), ] ) ) @@ -131,10 +131,9 @@ def _array(**members: object) -> dict[str, object]: _NOTE_CONTEXT, set(), ), - # A definition that allows user data allows a number that is not - # finite only where its configuration says `UserJSONValue`: not in a - # number, and not in a declaration it holds, which is reported where - # it is not JSON. + # A number that is not finite may stand only where the configuration + # says `UserJSONValue`: not in a number, and not in a declaration it + # holds, which is reported where it is not JSON. ( _array(**{"acme.mix": _mix({"name": "bytes"}, 1.5)}), _NOTE_CONTEXT, @@ -162,6 +161,13 @@ def _array(**members: object) -> dict[str, object]: _NOTE_CONTEXT, {(("acme.note", "x"), "unknown_key"), (("acme.note", "x"), "invalid_value")}, ), + # A key that is not a string is reported by the configuration's + # checker, and refuses the member. + ( + _array(**{"acme.note": {"note": 1, "must_understand": True, 5: 1}}), + _NOTE_CONTEXT, + {(("acme.note",), "invalid_type")}, + ), ], ids=[ "non-json-codec", @@ -172,6 +178,7 @@ def _array(**members: object) -> dict[str, object]: "user-data-where-annotated", "not-finite-elsewhere", "not-finite-under-unknown-key", + "non-string-key-in-a-member", ], ) def test_every_problem_in_a_document_is_reported( @@ -201,7 +208,7 @@ def test_every_problem_in_a_document_is_reported( def test_error_a_configuration_refuses_a_declaration_in_it_that_is_not_json() -> None: # Without a scope, as with one: the declaration is not JSON, and that is # reported where it is not. - definition = ArrayExtraFieldDefinition(name="acme.mix", configuration=_Mix, finite=False) + definition = ArrayExtraFieldDefinition(name="acme.mix", configuration=_Mix) configuration, problems = definition.read_configuration( _mix({"name": "bytes", "configuration": {"endian": math.nan}}, 1.5) ) @@ -243,14 +250,34 @@ def test_a_declaration_without_a_configuration_reads_up_to_the_last_level( ), ({"foo": _deep(JSON_DEPTH - 2)}, [(("foo",), "unknown_key")]), ({"kind": math.inf}, [(("kind",), "invalid_value")]), + # What is not JSON does not keep either reader from reporting every + # other problem. + ( + {"kind": "x", "foo": b"a"}, + [(("foo",), "unknown_key"), (("foo",), "invalid_type"), (("kind",), "invalid_value")], + ), + ({"foo": {1: 2}}, [(("foo",), "unknown_key"), (("foo",), "invalid_type")]), + ( + {"foo": _deep(JSON_DEPTH - 1)}, + [(("foo",), "unknown_key"), (("foo", 0), "invalid_value")], + ), + ], + ids=[ + "nan", + "two-keys", + "deepest", + "kind-not-finite", + "not-json-beside-a-wrong-value", + "non-string-key", + "past-the-levels", ], - ids=["nan", "two-keys", "deepest", "kind-not-finite"], ) def test_error_a_consolidated_envelope_refines_a_member_it_leaves_out( extra: dict[str, object], expected: list[tuple[Loc, str]] ) -> None: # Read alone or in its group, the envelope reports the same problems, - # in the same order, and counts depth from the root of the group. + # in the same order, and counts depth from the root of the group. A + # problem past the levels is compared by where it starts. array = json.loads(json.dumps(ZarrV3ArrayMetadata.create_default(shape=(4,)).to_json())) envelope = {"kind": "inline", "must_understand": False, "metadata": {"x": array}, **extra} group = { @@ -261,8 +288,8 @@ def test_error_a_consolidated_envelope_refines_a_member_it_leaves_out( } alone = read_consolidated_metadata_v3(envelope).problems in_group = read_group_metadata_v3(group).problems - assert [(problem.loc, problem.kind) for problem in alone] == expected - assert [(problem.loc, problem.kind) for problem in in_group] == [ + assert [(problem.loc[:2], problem.kind) for problem in alone] == expected + assert [(problem.loc[:3], problem.kind) for problem in in_group] == [ (("consolidated_metadata", *loc), kind) for loc, kind in expected ] diff --git a/packages/zarr-metadata/tests/v3/test_definitions.py b/packages/zarr-metadata/tests/v3/test_definitions.py index 07c398ac8d..5243fbcbe5 100644 --- a/packages/zarr-metadata/tests/v3/test_definitions.py +++ b/packages/zarr-metadata/tests/v3/test_definitions.py @@ -21,7 +21,7 @@ JSONValue, ValidationProblem, ) -from zarr_metadata._json import refine_json +from zarr_metadata._json import is_object, refine_json from zarr_metadata.definition import ( AcceptedDeclaration, Context, @@ -860,16 +860,31 @@ def test_error_null_is_not_a_declaration() -> None: assert (configuration, _locs(found)) == (None, [((), "invalid_type")]) -def test_error_a_value_that_is_not_json() -> None: - # The JSON is stored as `UNSET`, because no document can hold a value - # that is not JSON. Its name still identifies the definition that claims it. +@pytest.mark.parametrize("level", [math.nan, b"9"], ids=["not-finite", "bytes"]) +def test_error_a_value_that_is_not_json(level: object) -> None: + # Its name still identifies the definition that claims it, which + # reports where the value is not JSON. A number that is not finite is + # user data, so the refusal holds the declaration as written; anything + # else that is not JSON is stored as `UNSET`, because no document can + # hold it. resolved, found = resolve( - {"name": "gzip", "configuration": {"level": math.nan}}, CodecDefinition, CONTEXT + {"name": "gzip", "configuration": {"level": level}}, CodecDefinition, CONTEXT ) - assert resolved == RefusedDeclaration( - json=UNSET, name="gzip", read_as=CodecDefinition, definition=GZIP_CODEC - ) - assert _locs(found) == [(("configuration", "level"), "invalid_value")] + assert isinstance(resolved, RefusedDeclaration) + assert (resolved.name, resolved.definition) == ("gzip", GZIP_CODEC) + held = resolved.json + if isinstance(level, float): + assert is_object(held) + configuration = held["configuration"] + assert is_object(configuration) + assert (held["name"], set(held), math.isnan(cast("float", configuration["level"]))) == ( + "gzip", + {"name", "configuration"}, + True, + ) + else: + assert held is UNSET + assert [loc for loc, _ in _locs(found)] == [("configuration", "level")] def test_error_a_value_that_is_not_a_declaration() -> None: From 4fb9eed2c77aa8cbcef508f34f58df9748113902 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 13:18:40 +0100 Subject: [PATCH 15/27] fix(zarr-metadata): never refuse a declaration that is not JSON without saying why The envelope check counted depth from the declaration, so a container nested too deep under an envelope member it does not declare left the declaration's JSON unset with only an unknown key to explain it, and `read_configuration` put `None` where such a codec was. The envelope check now counts from the root, and a declaration whose JSON is unset is always reported with why it is not JSON (`_explained`, `_not_json`). A declaration holding a nested one that is not JSON, or whose number is not finite, is refused, so an accepted declaration always writes JSON. Its rules still run when every nested declaration has a name, read as written, so their problems are reported. A key that is not a string is reported with one message everywhere. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/changes/493.feature.md | 2 +- .../zarr-metadata/docs/validation-rules.md | 4 +- .../zarr-metadata/src/zarr_metadata/_json.py | 11 +-- .../src/zarr_metadata/_typed_json.py | 5 +- .../src/zarr_metadata/definition/__init__.py | 4 +- .../zarr_metadata/definition/_definition.py | 81 ++++++++++++++----- .../src/zarr_metadata/definition/_envelope.py | 13 +-- .../src/zarr_metadata/model/_group_v3.py | 8 +- .../src/zarr_metadata/v2/_definition.py | 4 +- .../src/zarr_metadata/v3/_definition.py | 16 ++-- .../tests/model/test_typed_document.py | 48 +++++++++++ 11 files changed, 146 insertions(+), 50 deletions(-) diff --git a/packages/zarr-metadata/changes/493.feature.md b/packages/zarr-metadata/changes/493.feature.md index 7cecef31e8..a08cd64f1c 100644 --- a/packages/zarr-metadata/changes/493.feature.md +++ b/packages/zarr-metadata/changes/493.feature.md @@ -1 +1 @@ -Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite may appear only where an annotation says `UserJSONValue`, such as `attributes` and unclaimed extension fields; `ExtraFieldDefinition`'s `finite` is removed, and a configuration says where with that annotation. A value that is not JSON no longer stops a declaration from being read, so every other problem in it is reported. `typed_json.check` follows the same annotations, and returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. +Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite may appear only where an annotation says `UserJSONValue`, such as `attributes` and unclaimed extension fields; `ExtraFieldDefinition`'s `finite` is removed, and a configuration says where with that annotation. A value that is not JSON no longer stops a declaration's own checks, so the other problems in it are reported; a declaration that holds one is still refused. `typed_json.check` follows the same annotations, and returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. diff --git a/packages/zarr-metadata/docs/validation-rules.md b/packages/zarr-metadata/docs/validation-rules.md index a8e1c133ab..d5c40c9964 100644 --- a/packages/zarr-metadata/docs/validation-rules.md +++ b/packages/zarr-metadata/docs/validation-rules.md @@ -9,8 +9,8 @@ context. For example: and [`node_type`](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#node-type)), - finite JSON numbers, except in `attributes`, in members that nothing - in the context reads, and where an extension field's configuration - says `UserJSONValue`, + in the context reads, and where a definition's configuration says + `UserJSONValue`, - non-negative [dimensions](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#array-metadata-shape), - one diff --git a/packages/zarr-metadata/src/zarr_metadata/_json.py b/packages/zarr-metadata/src/zarr_metadata/_json.py index f55081b1f6..931186ab06 100644 --- a/packages/zarr-metadata/src/zarr_metadata/_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/_json.py @@ -519,11 +519,7 @@ def _refine(value: object, loc: tuple[str | int, ...], *, finite: bool) -> _Refi found_in_members: list[ValidationProblem] = [] for key, item in cast("Mapping[object, object]", value).items(): if not isinstance(key, str): - found_in_members.append( - ValidationProblem( - loc, f"non-string key {shown_key(key)} in JSON object", "invalid_type" - ) - ) + found_in_members.append(non_string_key(key, loc)) continue member, found = _refine(item, (*loc, key), finite=finite) found_in_members.extend(found) @@ -610,6 +606,11 @@ def shown(value: object) -> str: return shown_by_python(value) +def non_string_key(key: object, loc: tuple[str | int, ...]) -> ValidationProblem: + """The problem with `key`, a key that is not a string, of the object at `loc`: the one problem every reader reports for it.""" + return ValidationProblem(loc, f"non-string key {shown_key(key)}", "invalid_type") + + def shown_key(key: object) -> str: """A non-string key as a message shows it: as Python shows it, since JSON has no such key to write. An integer with more digits than the interpreter writes is shown by its size.""" if isinstance(key, int) and not isinstance(key, bool): diff --git a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py index 940333605c..b425637bec 100644 --- a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py @@ -82,6 +82,7 @@ is_object, listed, nested_past_the_levels, + non_string_key, outside_of, refine_json, refine_user_data, @@ -863,7 +864,7 @@ def parse(value: object, loc: Loc) -> Parsed: found: list[ValidationProblem] = [] for key, entry in entries.items(): if not isinstance(key, str): - found.extend(problem(loc, f"non-string key {shown(key)}")) + found.append(non_string_key(key, loc)) continue if key in members: continue @@ -907,7 +908,7 @@ def parse(candidate: object, loc: Loc) -> Parsed: found: list[ValidationProblem] = [] for key, entry in entries.items(): if not isinstance(key, str): - found.extend(problem(loc, f"non-string key {shown(key)}")) + found.append(non_string_key(key, loc)) continue item, problems = value(entry, (*loc, key)) parsed[key] = item diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py index 00aa1201cd..26ba45078e 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py @@ -91,7 +91,9 @@ is checked without it. What the key holds must still be JSON, with every number finite, since no annotation admits anything else there. So a consumer that tolerates unknown keys can filter problems by kind and use -the result. The declaration is valid only +the result. A problem with the envelope (an extra member, or a +`must_understand` that is not a boolean) is reported and does not +refuse the declaration, which keeps its envelope as written. The declaration is valid only when there are no problems at all. Each problem stores the content of its message as data, as pydantic's errors and zod's issues do: `input` is the value found at `loc` (the `12` above), and `ctx` is what was diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index 3d381d2f98..1e1930266c 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -271,9 +271,9 @@ def _named_configuration( return named_configuration(value) @classmethod - def _envelope_problems(cls, value: object) -> Problems: - """Every reason `value` is not a valid envelope for a declaration of this kind in this format. The contents of the configuration are not checked.""" - return envelope_problems(value, allow_must_understand_false=False) + def _envelope_problems(cls, value: object, loc: Loc = ()) -> Problems: + """Every reason `value`, a declaration at `loc`, is not a valid envelope for a declaration of this kind in this format, located in the declaration. The contents of the configuration are not checked. Depth is counted from the root, where `loc` places the declaration.""" + return envelope_problems(value, loc, allow_must_understand_false=False) @classmethod def _envelope_json(cls, name: str, configuration: Mapping[str, JSONValue]) -> JSONValue: @@ -305,6 +305,11 @@ def _refined( refined, found = refine_user_data(data, loc) return (UNSET if len(found) != 0 else refined), () + @classmethod + def _not_json(cls, data: object, loc: Loc) -> Problems: + """Every reason `data`, a declaration of this kind at `loc`, is not JSON even as user data, as `_refined` finds them.""" + return refine_user_data(data, loc)[1] + @classmethod def _unread(cls, data: object, json: JSONValue | UNSET, loc: Loc) -> Problems: """Every problem of `data`, a declaration of this kind at `loc` that no definition reads, beyond its envelope's: its configuration must be JSON, every number finite, as `JSONValue` says. `json` is the declaration as `_refined` refined it.""" @@ -890,7 +895,8 @@ def _envelope(declaration: _NestedDeclaration) -> Problems: """The problems with a nested declaration's envelope, located at the declaration; for a declaration its kind does not read at all, the problems that keep it from being read.""" if len(declaration.problems) != 0: return declaration.problems - return _located(declaration.loc, declaration.kind._envelope_problems(_as_read(declaration))) + found = declaration.kind._envelope_problems(_as_read(declaration), declaration.loc) + return _located(declaration.loc, found) def _unread_problems(declaration: _NestedDeclaration) -> Problems: @@ -898,7 +904,13 @@ def _unread_problems(declaration: _NestedDeclaration) -> Problems: if len(declaration.problems) != 0: return declaration.problems unread = declaration.kind._unread(_as_read(declaration), declaration.json, declaration.loc) - return (*_envelope(declaration), *unread) + return _explained( + declaration.kind, + declaration.written, + declaration.json, + declaration.loc, + (*_envelope(declaration), *unread), + ) def _moved(declaration: _NestedDeclaration, loc: Loc) -> _NestedDeclaration: @@ -961,7 +973,7 @@ def typed_document(doc: Mapping[object, object], shape: type, at: Loc = ()) -> T problem in another, nesting depth counts from the root of the input, and a number that is not finite may be only where the annotation is `UserJSONValue` (a node's attributes). Each declaration is passed on - for a scope to read, with every reason it is not JSON. A member an open + for a scope to read, as its kind refines it. A member an open TypedDict does not declare is an extension field: what it holds is for the definition in scope that claims its key, so it is passed on as written. @@ -1074,7 +1086,7 @@ class AcceptedDeclaration(Generic[D]): """ json: JSONValue - """The declaration as written, refined (arrays as tuples). It is not used for equality.""" + """The declaration as written, refined as user data (arrays as tuples). An envelope member it should not have is kept, and reported. It is not used for equality.""" name: str """The name the declaration is written with, for example `"r16"`, even though its definition is filed under `r*`.""" definition: D @@ -1659,8 +1671,9 @@ def resolve( ) -> tuple[ResolvedDeclaration[D], Problems]: """Read `data` (one declaration) as a `kind` in `context`. Return the result of the reading, and every problem. - This runs all three steps for one declaration. `data` is refined to JSON and - its envelope is checked. An extra envelope member, a `configuration` that is not + This runs all three steps for one declaration. `data` is refined as its + kind refines declarations (`UNSET` when it is not JSON, and then read as + written), and its envelope is checked. An extra envelope member, a `configuration` that is not an object, and a `must_understand` that is not a boolean or is `false` are each a problem. The name is mapped to a definition in `context`. The configuration is checked against its TypedDict and by its rules. @@ -1773,9 +1786,18 @@ def _resolve_declaration( and later layers can still check that declaration. """ read = data if json is UNSET else json - envelope = _located(loc, kind._envelope_problems(read)) + envelope = _located(loc, kind._envelope_problems(read, loc)) resolved, found = _read(read, json, kind, context, loc) - return resolved, (*envelope, *found) + return resolved, _explained(kind, data, json, loc, (*envelope, *found)) + + +def _explained( + kind: type[Definition[Any]], data: object, json: JSONValue | UNSET, loc: Loc, problems: Problems +) -> Problems: + """`problems`, the problems found with `data`, a declaration of `kind` at `loc`, and every reason it is not JSON when it is not (`json` is `UNSET`) and nothing they report but an unknown key says so. A declaration that is not JSON is always refused, so it is never refused without a reason.""" + if json is not UNSET or not _usable(problems): + return problems + return (*problems, *kind._not_json(data, loc)) def _read( @@ -1824,25 +1846,30 @@ def _read( place = declaration.loc[len(at) :] placed = _moved(declaration, kind._in_configuration(loc, place)) if len(placed.problems) != 0: - # Not JSON, so refused as a document's declarations are. It has - # no name `_named` reads, so no configuration is built from it. + # Its kind does not read it at all, so it is refused as a + # document's declarations are. inner, found_inside = resolve_refined( - placed.written, None, placed.problems, placed.kind, context, placed.loc + placed.written, UNSET, placed.problems, placed.kind, context, placed.loc ) else: - inside.extend(_envelope(placed)) + envelope = _envelope(placed) inner, found_inside = _read( _as_read(placed), placed.json, placed.kind, context, placed.loc ) + found_inside = _explained( + placed.kind, placed.written, placed.json, placed.loc, (*envelope, *found_inside) + ) within[place] = inner - written[declaration.loc] = cast("JSONValue", document_json(inner)) + written[declaration.loc] = _held(inner) inside.extend(found_inside) inside.extend(_sized(placed, inner)) # The rules may look up a nested declaration by its name, so they run only # when every nested declaration has a name. Any other problem with a nested # declaration belongs to that declaration and is reported at its location, as with - # a document's declarations. + # a document's declarations. The declaration is accepted only when what it + # holds is JSON, so that it writes JSON. sound = _usable(found) and all(_named(declaration) for declaration in nested) + pure = all(_pure(inner) for inner in within.values()) configuration = ( cast( "Mapping[str, JSONValue]", @@ -1857,7 +1884,7 @@ def _read( ruled(definition, lambda: definition.rules(read_only(configuration), within), at) ) placed = _in_document(kind, loc, given is not None, own) - if configuration is None or json is UNSET or not _usable(placed): + if configuration is None or json is UNSET or not pure or not _usable(placed): refused = RefusedDeclaration( json=json, name=name, read_as=kind, definition=definition, nested=within ) @@ -1903,11 +1930,25 @@ def _in_document( def _named(declaration: _NestedDeclaration) -> bool: - """Whether a nested declaration has a name, and its configuration (if any) is an object.""" - name, _, malformed = declaration.kind._named_configuration(declaration.json) + """Whether a nested declaration has a name, and its configuration (if any) is an object, as written when it is not JSON.""" + name, _, malformed = declaration.kind._named_configuration(_as_read(declaration)) return name is not None and len(malformed) == 0 +def _held(inner: ResolvedDeclaration[Any]) -> JSONValue: + """A nested declaration as the configuration that holds it shows it to its rules: as a document writes it, or None when it is not JSON, as `typed_document` puts one back.""" + written = document_json(inner) + return None if written is UNSET else written + + +def _pure(inner: ResolvedDeclaration[Any]) -> bool: + """Whether a nested declaration, as a document writes it, is JSON with every number finite, so the declaration that holds it can be accepted and write JSON. A declaration that was read is; one that was refused is checked, since it is kept as written.""" + if not isinstance(inner, RefusedDeclaration): + return True + written = inner.json + return written is not UNSET and len(refine_json(written, ())[1]) == 0 + + def _given( shape: type, given: Mapping[str, object] | None, at: Loc ) -> tuple[object, Problems, tuple[_NestedDeclaration, ...]]: diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py b/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py index 8af23673d0..165c79741c 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py @@ -10,7 +10,7 @@ from typing import Final from zarr_metadata._common import JSONValue, ZarrV3NamedConfigJSON -from zarr_metadata._json import ValidationProblem, is_object, shown +from zarr_metadata._json import ValidationProblem, is_object, shown, within from zarr_metadata._typed_json import Loc, Parsed, Parser, parser, problem ENVELOPE_KEYS: frozenset[str] = frozenset({"name", "configuration", "must_understand"}) @@ -79,7 +79,7 @@ def _an_object(value: object, loc: Loc) -> Parsed: def envelope_problems( - value: object, *, allow_must_understand_false: bool + value: object, loc: Loc = (), *, allow_must_understand_false: bool ) -> tuple[ValidationProblem, ...]: """Every reason `value` is not a valid v3 declaration envelope. The contents of the configuration are not checked. @@ -88,11 +88,12 @@ def envelope_problems( `must_understand`, and no other keys. What its annotation cannot say is checked after it: the name must be a valid extension name under the spec, and `must_understand` must not be `false` where a reader must - understand the declaration. `resolve` calls this on a declaration it - has already narrowed to JSON. + understand the declaration. `loc` is where the declaration is, from the + root, so depth is counted from there; each problem is located in the + declaration. """ - _, found = _ENVELOPE(value, ()) - problems = list(found) + _, found = _ENVELOPE(value, loc) + problems = list(within(found, loc)) name, at = (value, ()) if isinstance(value, str) else (None, ("name",)) if is_object(value): name = value.get("name") diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py index 8133318241..bb4336e78a 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py @@ -26,13 +26,13 @@ is_object, json_text, nested_past_the_levels, + non_string_key, not_an_object, outside_of, prefixed, refine_user_data, said, shown, - shown_key, with_input, within, ) @@ -1119,11 +1119,7 @@ def _read_consolidated_v3( elif is_object(entries): for key, entry in entries.items(): if not isinstance(key, str): - problems.append( - ValidationProblem( - ("metadata",), f"non-string key {shown_key(key)}", "invalid_type" - ) - ) + problems.append(non_string_key(key, ("metadata",))) continue faults = _key_problems(key) problems.extend(faults) diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v2/_definition.py index 4f661edfee..4eb637b0ec 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/_definition.py @@ -219,7 +219,7 @@ def _refined( return (UNSET if len(found) != 0 else refined), found @classmethod - def _envelope_problems(cls, value: object) -> Problems: + def _envelope_problems(cls, value: object, loc: Loc = ()) -> Problems: if isinstance(value, str): bad = typestr_problem(value, ()) return () if bad is None else (bad,) @@ -304,7 +304,7 @@ def _refined( return (UNSET if len(found) != 0 else refined), found @classmethod - def _envelope_problems(cls, value: object) -> Problems: + def _envelope_problems(cls, value: object, loc: Loc = ()) -> Problems: if not is_object(value): return ( ValidationProblem( diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py index 6085b75bef..6552581801 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py @@ -584,7 +584,7 @@ def _named_configuration( return name, cast("Mapping[str, object]", configuration), () @classmethod - def _envelope_problems(cls, value: object) -> Problems: + def _envelope_problems(cls, value: object, loc: Loc = ()) -> Problems: name = cls._named_configuration(value)[0] if name is None: return ( @@ -612,6 +612,15 @@ def _refined( value, found = refine_user_data(data[name], loc) return (UNSET if len(found) != 0 else {name: value}), () + @classmethod + def _not_json(cls, data: object, loc: Loc) -> Problems: + # As `_refined` refines it: the member's value, at the member's + # location. + name = cls._named_configuration(data)[0] + if name is None or not is_object(data): + return refine_user_data(data, loc)[1] + return refine_user_data(data[name], loc)[1] + @classmethod def _unread(cls, data: object, json: JSONValue | UNSET, loc: Loc) -> Problems: # A member nothing claims is user data, like attributes: it need @@ -619,10 +628,7 @@ def _unread(cls, data: object, json: JSONValue | UNSET, loc: Loc) -> Problems: # unless `json` is `UNSET`. if json is not UNSET: return () - name = cls._named_configuration(data)[0] - if name is None or not is_object(data): - return () - return refine_user_data(data[name], loc)[1] + return cls._not_json(data, loc) @classmethod def _envelope_json(cls, name: str, configuration: Mapping[str, JSONValue]) -> JSONValue: diff --git a/packages/zarr-metadata/tests/model/test_typed_document.py b/packages/zarr-metadata/tests/model/test_typed_document.py index 13199da2b2..392f1576c3 100644 --- a/packages/zarr-metadata/tests/model/test_typed_document.py +++ b/packages/zarr-metadata/tests/model/test_typed_document.py @@ -22,6 +22,7 @@ from zarr_metadata.v3.definition import ( CORE_CONTEXT, ArrayExtraFieldDefinition, + CodecDefinition, DataTypeDefinition, ZarrV3Context, ) @@ -310,3 +311,50 @@ def test_error_a_consolidated_envelope_counts_depth_from_the_group() -> None: (("foo",), "invalid_value"), ] assert len(problems[1].loc) == JSON_DEPTH - 1 + + +@pytest.mark.parametrize("levels", [JSON_DEPTH - 2, JSON_DEPTH - 1], ids=["one-past", "two-past"]) +def test_error_a_declaration_counts_depth_from_the_root_under_an_envelope_member( + levels: int, +) -> None: + # A member the envelope does not declare is refined where it sits, from + # the root of the document, so what is nested too deep under it is + # reported, and the declaration is refused. + doc = _array(codecs=[{"name": "bytes", "x": _deep(levels)}]) + reading = read_array_metadata_v3(doc) + assert [(problem.loc[:4], problem.kind) for problem in reading.problems] == [ + (("codecs", 0, "x"), "unknown_key"), + (("codecs", 0, "x", 0), "invalid_value"), + ] + + +def test_error_a_configuration_with_a_nested_declaration_too_deep_is_refused() -> None: + # Without a scope, a nested declaration that is not JSON refuses the + # configuration that holds it, with every reason. + definition = ArrayExtraFieldDefinition(name="acme.mix", configuration=_Mix) + configuration, problems = definition.read_configuration( + _mix({"name": "bytes", "x": _deep(JSON_DEPTH - 1)}, 1.5) + ) + assert configuration is None + assert [(problem.loc[:3], problem.kind) for problem in problems] == [ + (("codec", "x"), "unknown_key"), + (("codec", "x", 0), "invalid_value"), + ] + + +def test_error_a_codec_holding_a_codec_that_is_not_json_is_refused() -> None: + # The inner codec's problem is its own, and the codec that holds it is + # refused too, so that an accepted codec always writes JSON. + sharding = { + "name": "sharding_indexed", + "configuration": { + "chunk_shape": [2], + "codecs": [{"name": "bytes", "configuration": {"endian": math.nan}}], + "index_codecs": [{"name": "bytes"}], + }, + } + resolved, problems = resolve(sharding, CodecDefinition, CORE_CONTEXT) + assert isinstance(resolved, RefusedDeclaration) + assert [(problem.loc, problem.kind) for problem in problems] == [ + (("configuration", "codecs", 0, "configuration", "endian"), "invalid_value") + ] From 789f2e380e809cf96c8b4b5c1ef5937463d63b88 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 13:48:41 +0100 Subject: [PATCH 16/27] fix(zarr-metadata): run a configuration's rules only on nested declarations that are JSON A nested declaration that was not JSON was shown to the rules of the declaration holding it as null, so a rule that reads a nested codec's name failed. A nested declaration now counts as named only when it is JSON, as the rules contract says, and the holder's rules do not run otherwise. The two hand-written non-string key messages in model/_shared.py use the shared `non_string_key` problem. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../zarr_metadata/definition/_definition.py | 8 +++++--- .../src/zarr_metadata/model/_shared.py | 10 +++------- .../zarr-metadata/tests/v3/test_definitions.py | 18 ++++++++++++++++++ 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index 1e1930266c..3ef3de2314 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -1930,13 +1930,15 @@ def _in_document( def _named(declaration: _NestedDeclaration) -> bool: - """Whether a nested declaration has a name, and its configuration (if any) is an object, as written when it is not JSON.""" - name, _, malformed = declaration.kind._named_configuration(_as_read(declaration)) + """Whether a nested declaration is JSON, has a name, and its configuration (if any) is an object. The rules of the declaration that holds it run only when each nested declaration is named, so a rule never sees a declaration that is not JSON.""" + if declaration.json is UNSET: + return False + name, _, malformed = declaration.kind._named_configuration(declaration.json) return name is not None and len(malformed) == 0 def _held(inner: ResolvedDeclaration[Any]) -> JSONValue: - """A nested declaration as the configuration that holds it shows it to its rules: as a document writes it, or None when it is not JSON, as `typed_document` puts one back.""" + """A nested declaration as the configuration that holds it shows it to its rules: as a document writes it. A declaration that is not JSON is never shown to a rule (see `_named`), so it is held as None only to keep the configuration a JSON value.""" written = document_json(inner) return None if written is UNSET else written diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_shared.py b/packages/zarr-metadata/src/zarr_metadata/model/_shared.py index a946c4a608..ec603fea8f 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_shared.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_shared.py @@ -12,10 +12,10 @@ ValidationProblem, is_array, is_object, + non_string_key, outside_of, refine_json, refine_user_data, - shown_key, with_input, within, ) @@ -54,9 +54,7 @@ def unexpected_keys( problems: list[ValidationProblem] = [] for key in doc: if not isinstance(key, str): - problems.append( - ValidationProblem((), f"non-string document key {shown_key(key)}", "invalid_type") - ) + problems.append(non_string_key(key, ())) elif key not in allowed: problems.append(ValidationProblem((key,), f"unexpected key {key!r}", "unknown_key")) return tuple(problems) @@ -92,9 +90,7 @@ def other_members( reserved_keys = standard_keys | additional_reserved_keys for key, value in doc.items(): if not isinstance(key, str): - problems.append( - ValidationProblem((), f"non-string top-level key {shown_key(key)}", "invalid_type") - ) + problems.append(non_string_key(key, ())) continue if key in reserved_keys: continue diff --git a/packages/zarr-metadata/tests/v3/test_definitions.py b/packages/zarr-metadata/tests/v3/test_definitions.py index 5243fbcbe5..9a4bdf2f64 100644 --- a/packages/zarr-metadata/tests/v3/test_definitions.py +++ b/packages/zarr-metadata/tests/v3/test_definitions.py @@ -950,6 +950,24 @@ def test_error_a_nested_envelope_s_problem_is_its_own_and_the_rules_are_asked() ] +@pytest.mark.parametrize("level", [math.nan, b"5"], ids=["nan", "bytes"]) +def test_error_a_container_rule_is_not_asked_of_a_nested_declaration_that_is_not_json( + level: object, +) -> None: + # The stack's rule reads each nested declaration's name. A nested + # declaration that holds a value of no JSON type is refused at its + # location, and the rule does not run: it would read a declaration that + # is not there. A non-finite number is user data, so the rule reads the + # declaration, and only its kind refuses it. + unread = {"name": "gzip", "configuration": {"level": level}} + declaration = {"name": "acme.stack", "configuration": {"codecs": [unread]}} + resolved, found = resolve(declaration, CodecDefinition, CONTEXT) + assert isinstance(resolved, RefusedDeclaration) + assert [problem.loc for problem in found] == [ + ("configuration", "codecs", 0, "configuration", "level") + ] + + def test_error_a_container_rule_is_not_asked_of_a_malformed_nested_declaration() -> None: # The stack's rule reads each nested declaration's name. A nested declaration with no # name is reported at its location, and the rule does not run, as it From 55425596ba5ae4eea027215e10420b182abbd0a7 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 13:59:55 +0100 Subject: [PATCH 17/27] test(zarr-metadata): pin that a container's rules run beside a nested non-finite number The test for a nested declaration that is not JSON had a NaN case that passed whether or not the holder's rules ran. Split it: one test shows the rules skip a nested declaration of no JSON type, and one shows they still run, and report the codec beside it, when the nested declaration holds a non-finite number. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../tests/v3/test_definitions.py | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/packages/zarr-metadata/tests/v3/test_definitions.py b/packages/zarr-metadata/tests/v3/test_definitions.py index 9a4bdf2f64..16809df9b7 100644 --- a/packages/zarr-metadata/tests/v3/test_definitions.py +++ b/packages/zarr-metadata/tests/v3/test_definitions.py @@ -950,21 +950,33 @@ def test_error_a_nested_envelope_s_problem_is_its_own_and_the_rules_are_asked() ] -@pytest.mark.parametrize("level", [math.nan, b"5"], ids=["nan", "bytes"]) -def test_error_a_container_rule_is_not_asked_of_a_nested_declaration_that_is_not_json( - level: object, -) -> None: +def test_error_a_container_rule_is_not_asked_of_a_nested_declaration_that_is_not_json() -> None: # The stack's rule reads each nested declaration's name. A nested # declaration that holds a value of no JSON type is refused at its # location, and the rule does not run: it would read a declaration that - # is not there. A non-finite number is user data, so the rule reads the - # declaration, and only its kind refuses it. - unread = {"name": "gzip", "configuration": {"level": level}} - declaration = {"name": "acme.stack", "configuration": {"codecs": [unread]}} + # is not there. So the bytes codec beside it is not reported. + unread = {"name": "gzip", "configuration": {"level": b"5"}} + declaration = {"name": "acme.stack", "configuration": {"codecs": [unread, "bytes"]}} resolved, found = resolve(declaration, CodecDefinition, CONTEXT) assert isinstance(resolved, RefusedDeclaration) - assert [problem.loc for problem in found] == [ - ("configuration", "codecs", 0, "configuration", "level") + assert _locs(found) == [ + (("configuration", "codecs", 0, "configuration", "level"), "invalid_type") + ] + + +def test_error_a_container_rule_is_asked_of_a_nested_declaration_holding_a_non_finite_number() -> ( + None +): + # A non-finite number is user data, so the nested declaration is JSON and + # the stack's rule runs: it refuses the bytes codec beside it. The + # nested codec's kind refuses its level. + unread = {"name": "gzip", "configuration": {"level": math.nan}} + declaration = {"name": "acme.stack", "configuration": {"codecs": [unread, "bytes"]}} + resolved, found = resolve(declaration, CodecDefinition, CONTEXT) + assert isinstance(resolved, RefusedDeclaration) + assert _locs(found) == [ + (("configuration", "codecs", 1), "invalid_value"), + (("configuration", "codecs", 0, "configuration", "level"), "invalid_value"), ] From ddacc86040c3dcd1a8a6e314198b7bd1f9682acd Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 14:36:41 +0100 Subject: [PATCH 18/27] refactor(zarr-metadata)!: leave whether JSON may hold a non-finite number to the JSON routines A number that is not finite is now JSON wherever the package reads one, as Python's `json` module reads and writes it. `refine_user_data`, the `UserJSONValue` alias and the `_user_json` checker leaf are removed, so a declaration, a configuration, attributes and an unclaimed member are all refined the same way. Where the spec gives a non-finite number a meaning, its own rule stays: a float fill value, or a complex component, that is a non-finite number is refused and must be written by its name. The rule now lives with the float fill value rules in both formats (`non_finite_fill_value`), and the `non_finite_fill_value` repair shares its naming (`non_finite_name`). An integer with more digits than the interpreter converts to text is still refused: without that guard, rule messages and `json_text`-based equality would raise on it, and `json.loads` never builds one. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/changes/493.feature.md | 2 +- .../zarr-metadata/docs/validation-rules.md | 7 +- .../src/zarr_metadata/_common.py | 12 +-- .../zarr-metadata/src/zarr_metadata/_json.py | 101 +++++++----------- .../src/zarr_metadata/_typed_json.py | 27 ++--- .../src/zarr_metadata/definition/__init__.py | 3 +- .../zarr_metadata/definition/_definition.py | 50 ++++++--- .../src/zarr_metadata/model/_array_v3.py | 7 +- .../src/zarr_metadata/model/_group_v2.py | 12 +-- .../src/zarr_metadata/model/_group_v3.py | 4 +- .../src/zarr_metadata/model/_repair.py | 15 +-- .../src/zarr_metadata/model/_shared.py | 14 +-- .../src/zarr_metadata/typed_json.py | 7 +- .../src/zarr_metadata/v2/data_type/scalar.py | 23 +++- .../src/zarr_metadata/v3/_common.py | 7 +- .../src/zarr_metadata/v3/_definition.py | 26 ++--- .../zarr_metadata/v3/_types/consolidated.py | 8 +- .../src/zarr_metadata/v3/array.py | 4 +- .../src/zarr_metadata/v3/consolidated.py | 2 +- .../src/zarr_metadata/v3/data_type/_float.py | 10 +- .../src/zarr_metadata/v3/group.py | 4 +- .../zarr-metadata/tests/model/test_array.py | 23 ++-- .../tests/model/test_consolidating.py | 2 +- .../tests/model/test_construction.py | 2 +- .../tests/model/test_extension_points.py | 9 +- .../tests/model/test_extra_fields.py | 9 -- .../tests/model/test_refine_json.py | 71 +++++------- .../tests/model/test_store_json.py | 37 +++---- .../tests/model/test_typed_document.py | 65 ++++++----- .../zarr-metadata/tests/test_problem_data.py | 10 +- .../zarr-metadata/tests/test_public_api.py | 1 - .../zarr-metadata/tests/test_typed_json.py | 40 ++----- .../zarr-metadata/tests/v2/test_data_types.py | 5 + .../tests/v3/test_definitions.py | 12 +-- .../tests/v3/test_fill_values.py | 4 +- 35 files changed, 271 insertions(+), 364 deletions(-) diff --git a/packages/zarr-metadata/changes/493.feature.md b/packages/zarr-metadata/changes/493.feature.md index a08cd64f1c..7c15779527 100644 --- a/packages/zarr-metadata/changes/493.feature.md +++ b/packages/zarr-metadata/changes/493.feature.md @@ -1 +1 @@ -Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite may appear only where an annotation says `UserJSONValue`, such as `attributes` and unclaimed extension fields; `ExtraFieldDefinition`'s `finite` is removed, and a configuration says where with that annotation. A value that is not JSON no longer stops a declaration's own checks, so the other problems in it are reported; a declaration that holds one is still refused. `typed_json.check` follows the same annotations, and returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. +Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite (`NaN`, `Infinity`, `-Infinity`, which Python's `json` module reads and writes) is now JSON everywhere: whether a document may hold one is left to the routines that read and write its text. A float's non-finite fill value must still be written by its name, as each spec says, in v2 as in v3. `refine_user_data`, `UserJSONValue` and `ExtraFieldDefinition`'s `finite` are removed. A value that is not JSON no longer stops a declaration's own checks, so the other problems in it are reported; a declaration that holds one is still refused. `typed_json.check` returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. diff --git a/packages/zarr-metadata/docs/validation-rules.md b/packages/zarr-metadata/docs/validation-rules.md index d5c40c9964..b1b17d3eb2 100644 --- a/packages/zarr-metadata/docs/validation-rules.md +++ b/packages/zarr-metadata/docs/validation-rules.md @@ -8,9 +8,10 @@ context. For example: ([`zarr_format`](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#zarr-format) and [`node_type`](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#node-type)), -- finite JSON numbers, except in `attributes`, in members that nothing - in the context reads, and where a definition's configuration says - `UserJSONValue`, +- a float's non-finite fill value written by its name (`"NaN"`, + `"Infinity"`, `"-Infinity"`); whether JSON text may hold a non-finite + number anywhere else is left to the JSON routines that read and write + it, - non-negative [dimensions](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#array-metadata-shape), - one diff --git a/packages/zarr-metadata/src/zarr_metadata/_common.py b/packages/zarr-metadata/src/zarr_metadata/_common.py index ddf590e660..f56c6e94b9 100644 --- a/packages/zarr-metadata/src/zarr_metadata/_common.py +++ b/packages/zarr-metadata/src/zarr_metadata/_common.py @@ -34,16 +34,10 @@ self-reference is a named recursion point that pydantic can resolve when building a `TypeAdapter`; a bare recursive `TypeAlias` raises `PydanticUserError`/`RecursionError` at validation time. -""" - -UserJSONValue = TypeAliasType("UserJSONValue", JSONValue) -"""User data in a document, such as a node's attributes: a `JSONValue` in which a number may also be `NaN`, `Infinity` or `-Infinity`. -The spec only requires attributes to be JSON values, and zarr-python -writes these numbers as bare tokens, so a reader accepts them where a -document holds user data. A configuration member annotated with this -alias is checked that way; a member annotated `JSONValue` must hold -finite numbers, as RFC 8259 requires. +A number may be `NaN`, `Infinity` or `-Infinity`, which Python's `json` +module reads and writes: whether a document may hold them is left to the +routines that read and write its text. """ diff --git a/packages/zarr-metadata/src/zarr_metadata/_json.py b/packages/zarr-metadata/src/zarr_metadata/_json.py index 931186ab06..9e850be098 100644 --- a/packages/zarr-metadata/src/zarr_metadata/_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/_json.py @@ -1,8 +1,10 @@ """JSON values and the problems found in them. This is the lowest layer of the reader. `refine_json` is the single walk that both normalizes and checks a value. -`refine_user_data` is the same walk over user data, where a non-finite -number is kept as a float. +Whether JSON text may hold a non-finite number is left to the JSON +routines that read and write it. An integer with more digits than the +interpreter converts to text is refused, so every message and comparison +can still write it; `json.loads` never builds one. Every layer (the checker, the definitions and the model) reports with `ValidationProblem` and `MetadataValidationError`. """ @@ -11,7 +13,6 @@ import dataclasses import json -import math from collections.abc import Callable, Iterator, Mapping, Sequence from dataclasses import dataclass from types import MappingProxyType @@ -321,7 +322,7 @@ def _holdable(value: object) -> bool: nested deeper than that. Such a value is not stored, because `is_canonical_json` rejects it. """ - return is_canonical_json(value, finite=False) + return is_canonical_json(value) def not_an_object(value: object) -> tuple[ValidationProblem, ...]: @@ -330,7 +331,7 @@ def not_an_object(value: object) -> tuple[ValidationProblem, ...]: def validate_json(value: object, loc: tuple[str | int, ...] = ()) -> tuple[ValidationProblem, ...]: - """Return every reason that `value`, located at `loc`, is not JSON, each at its own location: a non-finite float, a non-string key, a value of no JSON type, or nesting deeper than `JSON_DEPTH`, counted from the document root above `loc`.""" + """Return every reason that `value`, located at `loc`, is not JSON, each at its own location: a non-string key, a value of no JSON type, or nesting deeper than `JSON_DEPTH`, counted from the document root above `loc`.""" return with_input(refine_json(value, loc)[1], value, loc) @@ -345,12 +346,12 @@ def is_object(value: object) -> TypeGuard[Mapping[object, object]]: def refined_object(value: object) -> dict[str, JSONValue]: - """Refine `value`, an object that a read found no problems in, as user data. The result is the document a model holds. + """Refine `value`, an object that a read found no problems in. The result is the document a model holds. Raises `TypeError` if `value` is not an object. This cannot happen after a read that found no problems. """ - refined, _ = refine_user_data(value) + refined, _ = refine_json(value) if not isinstance(refined, dict): msg = f"expected an object a read found nothing wrong with, got {shown(value)}" raise TypeError(msg) @@ -394,30 +395,20 @@ def refine_json( """`value` as JSON with arrays as tuples, or None with every reason it is not JSON. A single walk both normalizes and checks: a mapping becomes a `dict` - with string keys, a sequence becomes a tuple, and a float must be - finite. For a value that is not JSON, the result is None, with the - problems located at the leaves that are not JSON. JSON's `null` is - also None, but with no problems, so `value` is JSON exactly when there - are no problems. + with string keys, and a sequence becomes a tuple. For a value that is + not JSON, the result is None, with the problems located at the leaves + that are not JSON. JSON's `null` is also None, but with no problems, so + `value` is JSON exactly when there are no problems. + + A float is JSON whatever its value. Python's `json` module reads and + writes `NaN`, `Infinity` and `-Infinity`, and whether a document may + hold them is left to the routines that read and write its text. Where + the spec gives such a number a meaning (a fill value), its own rule + says how it is written. An integer with more digits than the + interpreter converts to text is not JSON, since no message, comparison + or writer could write it. """ - return _refine(value, loc, finite=True) - - -def refine_user_data( - value: object, loc: tuple[str | int, ...] = () -) -> tuple[JSONValue | None, tuple[ValidationProblem, ...]]: - """Refine user data the same way `refine_json` refines JSON, but keep a non-finite number as a float. - - A node's attributes are user data. The spec only requires each to be a - JSON value, and does not interpret any of them. zarr-python writes them - with the defaults of Python's `json` module, so an attribute can hold - `NaN`, `Infinity` or `-Infinity` (for example xarray's `_FillValue` or - a CF `missing_value`), which RFC 8259 does not allow. Wherever the spec - interprets a value, it writes those numbers as strings. So a validator - uses `refine_json` for values the spec interprets, and this function - only for user data. - """ - return _refine(value, loc, finite=False) + return _refine(value, loc) _Refined = tuple[JSONValue | None, tuple[ValidationProblem, ...]] @@ -464,22 +455,18 @@ def within( return tuple(dataclasses.replace(p, loc=p.loc[len(at) :]) for p in problems) -def _refine(value: object, loc: tuple[str | int, ...], *, finite: bool) -> _Refined: - """`refine_json`, but a non-finite number counts as JSON unless `finite` is true.""" +def _refine(value: object, loc: tuple[str | int, ...]) -> _Refined: + """`refine_json` of `value` at `loc`.""" # Check the exact types `json.loads` builds first, by type alone. Nearly # every value is one of these, so only the remaining values reach the # subclass checks below (a `StrEnum` member, an `IntEnum` member, a # mapping proxy). - if type(value) is str or type(value) is bool or value is None: + if type(value) is str or type(value) is bool or type(value) is float or value is None: return value, () if type(value) is int: if _writable(value): return value, () return None, (ValidationProblem(loc, _too_many_digits(value), "invalid_value"),) - if type(value) is float: - if not finite or math.isfinite(value): - return value, () - return None, (_not_finite(value, loc),) cls = type(value) if cls is dict: mapping = True @@ -487,9 +474,7 @@ def _refine(value: object, loc: tuple[str | int, ...], *, finite: bool) -> _Refi mapping = False else: if isinstance(value, float): - if not finite or math.isfinite(value): - return float(value), () - return None, (_not_finite(value, loc),) + return float(value), () if isinstance(value, int) and not isinstance(value, bool) and not _writable(value): return None, (ValidationProblem(loc, _too_many_digits(value), "invalid_value"),) if isinstance(value, bool): @@ -521,7 +506,7 @@ def _refine(value: object, loc: tuple[str | int, ...], *, finite: bool) -> _Refi if not isinstance(key, str): found_in_members.append(non_string_key(key, loc)) continue - member, found = _refine(item, (*loc, key), finite=finite) + member, found = _refine(item, (*loc, key)) found_in_members.extend(found) if len(found) == 0: members[key] = member @@ -529,18 +514,13 @@ def _refine(value: object, loc: tuple[str | int, ...], *, finite: bool) -> _Refi entries: list[JSONValue] = [] found_in_entries: list[ValidationProblem] = [] for index, item in enumerate(cast("Sequence[object]", value)): - entry, found = _refine(item, (*loc, index), finite=finite) + entry, found = _refine(item, (*loc, index)) found_in_entries.extend(found) if len(found) == 0: entries.append(entry) return (tuple(entries) if len(found_in_entries) == 0 else None), tuple(found_in_entries) -def _not_finite(value: float, loc: tuple[str | int, ...]) -> ValidationProblem: - """The problem for a non-finite number at `loc`, since JSON has no such numbers.""" - return ValidationProblem(loc, f"non-finite float {value!r} is not JSON", "invalid_value") - - def _too_many_digits(value: int) -> str: """The message for an integer the interpreter will not convert to text, stating its size.""" return ( @@ -587,7 +567,7 @@ def shown(value: object) -> str: """`value` as a problem's message shows it: as JSON (`null`, `[1, 2]`), or as its repr when it is not JSON. A value the interpreter will not write (an integer with too many digits, or a value nested too deep) is described instead.""" if isinstance(value, int) and not isinstance(value, bool) and not _writable(value): return f"an integer of {value.bit_length()} bits" - refined, problems = _refine(value, (), finite=False) + refined, problems = _refine(value, ()) if any(problem.message == _PAST_THE_LEVELS for problem in problems): # Nested deeper than `JSON_DEPTH`. Say so instead of using the repr, # which overflows at a depth set by the interpreter and platform. @@ -699,35 +679,31 @@ def _set_type(value: object) -> str: return json_type(value) -def is_canonical_json(value: object, *, finite: bool = True) -> TypeGuard[JSONValue]: +def is_canonical_json(value: object) -> TypeGuard[JSONValue]: """Whether `value` already uses the concrete containers in `JSONValue`, nested no deeper than `JSON_DEPTH`. - A non-finite number counts only when `finite` is false, as in user data - such as attributes: the document's reader decides where such a number - is allowed. The walk uses one frame per level of - nesting, `JSON_DEPTH` at most, as `refine_json` does. A reader does not - accept a container deeper than that as JSON, so this function does not - either, and the walk stops there. + The walk uses one frame per level of nesting, `JSON_DEPTH` at most, as + `refine_json` does. A reader does not accept a container deeper than + that as JSON, so this function does not either, and the walk stops + there. """ - return _is_canonical(value, 0, finite=finite) + return _is_canonical(value, 0) -def _is_canonical(value: object, depth: int, *, finite: bool) -> bool: +def _is_canonical(value: object, depth: int) -> bool: """`is_canonical_json` of `value`, which is `depth` levels deep.""" - if isinstance(value, float): - return not finite or math.isfinite(value) - if isinstance(value, (str, int, bool)) or value is None: + if isinstance(value, (str, int, float, bool)) or value is None: return True if depth >= JSON_DEPTH: return False if is_list_or_tuple(value): for item in value: # noqa: SIM110 - a loop, not a generator, is one frame per level - if not _is_canonical(item, depth + 1, finite=finite): + if not _is_canonical(item, depth + 1): return False return True if is_object(value): for key, item in value.items(): - if not isinstance(key, str) or not _is_canonical(item, depth + 1, finite=finite): + if not isinstance(key, str) or not _is_canonical(item, depth + 1): return False return True return False @@ -848,7 +824,6 @@ def arrays_to_tuples(obj: object) -> object: "parse_json", "prefixed", "refine_json", - "refine_user_data", "refused_kind", "said", "shown", diff --git a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py index b425637bec..c145c15c3c 100644 --- a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py @@ -71,7 +71,7 @@ import typing_extensions from typing_extensions import NoExtraItems, TypeIs, is_typeddict -from zarr_metadata._common import JSONValue, UserJSONValue +from zarr_metadata._common import JSONValue from zarr_metadata._json import ( JSON_DEPTH, ValidationProblem, @@ -85,7 +85,6 @@ non_string_key, outside_of, refine_json, - refine_user_data, shown, with_input, ) @@ -612,7 +611,6 @@ def has_shape(shape: str | None, value: object) -> bool: # document holds it, not only canonical JSON: a scalar comes back as the # JSON value it stands for (a `StrEnum` member as its string), an array of # any kind of sequence comes back as a tuple, and any mapping as a dict. A -# number must be finite, except in a value annotated `UserJSONValue`, and a # container must sit within `JSON_DEPTH` levels of the root of the # document, which `loc` locates it below. So a value that is not JSON is # reported where it sits, as `refine_json` reports it, and does not hide a @@ -622,10 +620,8 @@ def has_shape(shape: str | None, value: object) -> bool: def _plain(value: object) -> bool: """Whether `value` is a JSON scalar of a type `json.loads` builds, which needs no refining. Nearly every value is one, so this is checked first, by type alone.""" cls = type(value) - if cls is str or cls is bool or value is None: + if cls is str or cls is bool or cls is float or value is None: return True - if cls is float: - return math.isfinite(cast("float", value)) return cls is int and cast("int", value).bit_length() <= 64 @@ -666,19 +662,12 @@ def parse(value: object, loc: Loc) -> Parsed: def _json(value: object, loc: Loc) -> Parsed: - """A member annotated `JSONValue`: JSON as RFC 8259 defines it, refined, or every reason it is not JSON, each where it sits.""" + """A member annotated `JSONValue`: JSON, refined, or every reason it is not JSON, each where it sits.""" refined, found = refine_json(value, loc) return (value if len(found) != 0 else refined), found -def _user_json(value: object, loc: Loc) -> Parsed: - """A member annotated `UserJSONValue`: JSON in which a number need not be finite, refined, or every other reason it is not JSON.""" - refined, found = refine_user_data(value, loc) - return (value if len(found) != 0 else refined), found - - _JSON: Final[Parser] = _json -_USER_JSON: Final[Parser] = _user_json def one_of(allowed: tuple[object, ...]) -> Parser: @@ -871,8 +860,7 @@ def parse(value: object, loc: Loc) -> Parsed: if extra is None: found.extend(problem((*loc, key), f"unexpected key {key!r}", "unknown_key")) # Left out, but still refined: a value that is not JSON is - # a problem whatever key holds it, and no annotation says - # this one may hold a number that is not finite. + # a problem whatever key holds it. found.extend(refine_json(entry, (*loc, key))[1]) continue parsed[key], problems = extra(entry, (*loc, key)) @@ -1394,8 +1382,6 @@ def _compile_type(inner: object, leaf: Leaf, building: _Building) -> Parser | No return _NULL if inner is JSONValue: return _JSON - if inner is UserJSONValue: - return _USER_JSON origin = get_origin(inner) if origin is Literal: return _literal(inner) @@ -1581,9 +1567,8 @@ def check( ) -> tuple[T | None, tuple[ValidationProblem, ...]]: """Type-check `value` as `shape`, a TypedDict. Returns the typed value or None, and every problem. - The check refines `value` as it goes (arrays as tuples, string keys, - a number finite except where the annotation is `UserJSONValue`), so a - part that is not JSON is reported where it sits, beside the problems + The check refines `value` as it goes (arrays as tuples, string keys), + so a part that is not JSON is reported where it sits, beside the problems of every other member. Each problem is located under `loc`. The returned value holds only what `shape` allows. A key that a closed TypedDict does not declare is reported as `unknown_key` and left out, and the value is still returned. Any other diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py index 26ba45078e..e093160db5 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py @@ -88,8 +88,7 @@ kind)`, with `kind` one of `invalid_type`, `invalid_value`, `missing_key`, `unknown_key` and `invalid_json`. A declaration with an unknown key is still read: the key is reported, and the configuration -is checked without it. What the key holds must still be JSON, with every -number finite, since no annotation admits anything else there. So a +is checked without it. What the key holds must still be JSON. So a consumer that tolerates unknown keys can filter problems by kind and use the result. A problem with the envelope (an extra member, or a `must_understand` that is not a boolean) is reported and does not diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index 3ef3de2314..1871aa418a 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -40,6 +40,7 @@ import dataclasses import functools +import math from collections.abc import Callable, Iterable, Iterator, Mapping from dataclasses import dataclass from types import MappingProxyType @@ -74,7 +75,6 @@ is_tuple, json_text, refine_json, - refine_user_data, said, shown, with_input, @@ -135,6 +135,29 @@ def no_fill_value_default(*_: object) -> UNSET: return UNSET +def non_finite_name(value: object) -> str | None: + """The name both formats' specs give `value`, a number that is not finite, as a float fill value: `"NaN"`, `"Infinity"` or `"-Infinity"`. None for any other value.""" + if not isinstance(value, float) or math.isfinite(value): + return None + if math.isnan(value): + return "NaN" + return "Infinity" if value > 0 else "-Infinity" + + +def non_finite_fill_value(value: object) -> tuple[ValidationProblem, ...]: + """The problem with `value`, a float fill value or complex fill value component, if it is a number that is not finite. Each spec writes such a value by its name (`non_finite_name`), a string, so the value means the same to a reader whose JSON has no such number. Whether the document's JSON may hold the number at all is for the routines that read its text.""" + name = non_finite_name(value) + if name is None: + return () + return ( + ValidationProblem( + (), + f"expected a non-finite fill value written by its name, {name!r}, got the number {name}", + "invalid_value", + ), + ) + + @dataclass(frozen=True, slots=True, eq=False) class ConstantFillValue: """A data type's default fill value that is the same for every configuration, such as `0` for `int8`. @@ -295,24 +318,23 @@ def _refined( ) -> tuple[JSONValue | UNSET, Problems]: """`data`, a declaration of this kind at `loc`, as the JSON a reading of it holds (`UNSET` when it is not JSON), and every problem that keeps a definition from reading it at all. `definition` is the definition that claims the declaration, if any. - By default nothing keeps a declaration from being read, and it is - refined as user data, so a number need not be finite. What it may + By default nothing keeps a declaration from being read. What it may hold is decided by the checks that read it, each by its annotation: its envelope's, then its definition's configuration, or `_unread` when nothing claims it. Each runs on the declaration as written when it is not JSON, so every problem is reported. """ - refined, found = refine_user_data(data, loc) + refined, found = refine_json(data, loc) return (UNSET if len(found) != 0 else refined), () @classmethod def _not_json(cls, data: object, loc: Loc) -> Problems: - """Every reason `data`, a declaration of this kind at `loc`, is not JSON even as user data, as `_refined` finds them.""" - return refine_user_data(data, loc)[1] + """Every reason `data`, a declaration of this kind at `loc`, is not JSON, as `_refined` finds them.""" + return refine_json(data, loc)[1] @classmethod def _unread(cls, data: object, json: JSONValue | UNSET, loc: Loc) -> Problems: - """Every problem of `data`, a declaration of this kind at `loc` that no definition reads, beyond its envelope's: its configuration must be JSON, every number finite, as `JSONValue` says. `json` is the declaration as `_refined` refined it.""" + """Every problem of `data`, a declaration of this kind at `loc` that no definition reads, beyond its envelope's: its configuration must be JSON, as `JSONValue` says. `json` is the declaration as `_refined` refined it.""" given = cls._named_configuration(data)[1] if given is None: return () @@ -935,8 +957,7 @@ def _configuration_checked( still returned. This matches how the checker reports and leaves out a key that a closed TypedDict does not declare. The check refines `value` as it goes, so a part that is not JSON is reported where it sits, - beside every other problem, and a number that is not finite is a - problem except where the TypedDict says `UserJSONValue`. No scope reads + beside every other problem. No scope reads a nested declaration here, so its configuration is checked as an unread one (`_unread`). """ @@ -970,9 +991,8 @@ def typed_document(doc: Mapping[object, object], shape: type, at: Loc = ()) -> T The document is checked as any configuration is, by the checker its TypedDict compiles to, which refines each value where it reads it. So each member is checked on its own, a problem in one does not hide a - problem in another, nesting depth counts from the root of the input, - and a number that is not finite may be only where the annotation is - `UserJSONValue` (a node's attributes). Each declaration is passed on + problem in another, and nesting depth counts from the root of the + input. Each declaration is passed on for a scope to read, as its kind refines it. A member an open TypedDict does not declare is an extension field: what it holds is for the definition in scope that claims its key, so it is passed on as @@ -1086,7 +1106,7 @@ class AcceptedDeclaration(Generic[D]): """ json: JSONValue - """The declaration as written, refined as user data (arrays as tuples). An envelope member it should not have is kept, and reported. It is not used for equality.""" + """The declaration as written, refined (arrays as tuples). An envelope member it should not have is kept, and reported. It is not used for equality.""" name: str """The name the declaration is written with, for example `"r16"`, even though its definition is filed under `r*`.""" definition: D @@ -1232,7 +1252,7 @@ class RefusedDeclaration(Generic[D]): """A declaration that could not be read: it is not a declaration at all, not JSON, or rejected by the definition that claims its name. Its problems explain why.""" json: JSONValue | UNSET - """The declaration as written, refined as user data (arrays as tuples, any number). `UNSET` when it is not JSON even so, which no document can contain.""" + """The declaration as written, refined (arrays as tuples). `UNSET` when it is not JSON, which no document can contain.""" name: str | None """The name the declaration is written with; None when it has no name.""" read_as: type[Definition[Any]] @@ -2188,6 +2208,8 @@ def _replaced(value: JSONValue, path: Loc, new: JSONValue) -> JSONValue: "kind_of", "named_configuration", "no_rules", + "non_finite_fill_value", + "non_finite_name", "own_key", "read_found", "read_only", diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py index d2b7d9ec33..4193ae09bf 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py @@ -291,11 +291,8 @@ def read_extra_fields_v3( Returns three values: each member that is JSON, refined; each member as the scope read it, by key; and every problem, located in the document. A member that a definition in `context` claims is read by that - definition: it must be an object, which may hold a number that is not - finite only where the definition's configuration says `UserJSONValue`. - Any other member is not read: it is an - `UnclaimedDeclaration`, and, like attributes, need only be JSON as Python's - `json` module reads it. + definition: it must be an object. Any other member is not read: it is + an `UnclaimedDeclaration`, and, like attributes, need only be JSON. """ values: dict[str, JSONValue] = {} declarations: dict[str, ResolvedDeclaration[Any]] = {} diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_group_v2.py b/packages/zarr-metadata/src/zarr_metadata/model/_group_v2.py index cbd34fb85f..71395afdfb 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_group_v2.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_group_v2.py @@ -24,7 +24,6 @@ object_at, prefixed, refine_json, - refine_user_data, refined_object, said, shown, @@ -719,12 +718,8 @@ def _read_consolidated_v2( ]: """Read `data`, a `.zmetadata` document. Return the document as read, with its keys in the order it writes them and each entry as read; the model of each node read in `context`, by path; the entry key of each node's files, by path and then by file name; and every problem, located in the document. - Each entry is read as the kind of document its key names. An entry - for a node's file is refined as user data, and its reader judges each - value the spec interprets: a `.zattrs` entry is user data, and a - `.zarray` or `.zgroup` reader refuses a non-finite number in a member - the spec defines, as it does in a store. Any other entry must be JSON - by RFC 8259. A `.zarray` or `.zgroup` entry is read as that document, + Each entry is read as the kind of document its key names, and must be + JSON. A `.zarray` or `.zgroup` entry is read as that document, merged with its sibling `.zattrs`. Its problems are located under its own entry, and problems with the attributes under the `.zattrs` entry. The nodes and their files are empty when there is any problem. @@ -752,8 +747,7 @@ def _read_consolidated_v2( for key, value in entries.items(): if not isinstance(key, str): continue - refine = refine_user_data if key.rsplit("/", 1)[-1] in _NODE_FILES else refine_json - entry, found = refine(value, ("metadata", key)) + entry, found = refine_json(value, ("metadata", key)) problems.extend(found) refined[key] = entry nodes: dict[str, ZarrV2NodeMetadata] = {} diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py index bb4336e78a..98c5a635c1 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py @@ -30,7 +30,7 @@ not_an_object, outside_of, prefixed, - refine_user_data, + refine_json, said, shown, with_input, @@ -1029,7 +1029,7 @@ def _read_node_model( # Use the model's own reading, unless the document is nested too # deep at its listed location. In that case, a read from that # location reports the problem. - _, past = refine_user_data(document, at) + _, past = refine_json(document, at) if len(past) != 0: return _read_node_v3(document, context, at) moved = entry.with_context(context) diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py index 679a584fc8..78511c26d5 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py @@ -17,7 +17,6 @@ from __future__ import annotations -import math from collections.abc import Mapping from dataclasses import dataclass from typing import TYPE_CHECKING, Annotated, Literal, TypeAlias, TypedDict, cast @@ -37,6 +36,7 @@ from zarr_metadata.definition._context import ( scoped, ) +from zarr_metadata.definition._definition import non_finite_name from zarr_metadata.model._group_v2 import ( ZarrV2ConsolidatedMetadataReading, ZarrV2NodeMetadataReading, @@ -423,14 +423,14 @@ def _non_finite_named( """`document`, an array of either format with a `fill_value` of a float data type when `is_float` and of a complex one otherwise, with a non-finite fill value, or complex fill value component, written by its name. Each name written is added to `repairs`, located under `at`.""" fill_value = document["fill_value"] if is_float: - name = _non_finite_name(fill_value) + name = non_finite_name(fill_value) if name is None: return document repairs.append(_non_finite_repair((*at, "fill_value"), name, "a fill value")) return {**document, "fill_value": name} if not is_list_or_tuple(fill_value) or len(fill_value) != 2: return document - names = [_non_finite_name(component) for component in fill_value] + names = [non_finite_name(component) for component in fill_value] if all(name is None for name in names): return document repairs.extend( @@ -445,15 +445,6 @@ def _non_finite_named( return {**document, "fill_value": repaired} -def _non_finite_name(value: object) -> str | None: - """The name the v2 spec gives `value`, a non-finite float: `"NaN"`, `"Infinity"` or `"-Infinity"`. None for any other value.""" - if not isinstance(value, float) or math.isfinite(value): - return None - if math.isnan(value): - return "NaN" - return "Infinity" if value > 0 else "-Infinity" - - def _non_finite_repair(loc: Loc, name: str, what: str) -> Repair: return Repair( loc, diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_shared.py b/packages/zarr-metadata/src/zarr_metadata/model/_shared.py index ec603fea8f..61568224e1 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_shared.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_shared.py @@ -15,7 +15,6 @@ non_string_key, outside_of, refine_json, - refine_user_data, with_input, within, ) @@ -79,12 +78,7 @@ def other_members( additional_reserved_keys: frozenset[str] = frozenset(), at: Loc = (), ) -> tuple[dict[str, JSONValue], tuple[ValidationProblem, ...]]: - """Each member outside `standard_keys`, refined as user data, and every problem found in them. A member that is not JSON is left out of the result. - - The spec does not interpret such a member, so like attributes, and - like a v3 member that nothing claims, it may hold `NaN`, `Infinity` - and `-Infinity`. - """ + """Each member outside `standard_keys`, refined, and every problem found in them. A member that is not JSON is left out of the result.""" members: dict[str, JSONValue] = {} problems: list[ValidationProblem] = [] reserved_keys = standard_keys | additional_reserved_keys @@ -94,7 +88,7 @@ def other_members( continue if key in reserved_keys: continue - refined, found = refine_user_data(value, (*at, key)) + refined, found = refine_json(value, (*at, key)) problems.extend(within(found, at)) if len(found) == 0: members[key] = refined @@ -278,7 +272,7 @@ def validate_attributes(value: object) -> tuple[ValidationProblem, ...]: def attributes_of( value: object, at: Loc = () ) -> tuple[dict[str, JSONValue] | None, tuple[ValidationProblem, ...]]: - """An `attributes` value refined as user data, and every problem `validate_attributes` finds. The value is None when it is not an object with string keys, or holds a value that is not JSON. + """An `attributes` value refined, and every problem `validate_attributes` finds. The value is None when it is not an object with string keys, or holds a value that is not JSON. `at` is the location, within the input document, of the document that holds the attributes. Nesting depth is counted from the root of @@ -296,7 +290,7 @@ def attributes_of( for key, item in value.items(): if not isinstance(key, str): continue - refined, found = refine_user_data(item, (*at, "attributes", key)) + refined, found = refine_json(item, (*at, "attributes", key)) problems.extend(found) attributes[key] = refined return (attributes if len(problems) == 0 else None), within(problems, at) diff --git a/packages/zarr-metadata/src/zarr_metadata/typed_json.py b/packages/zarr-metadata/src/zarr_metadata/typed_json.py index b98d392927..b666a915e5 100644 --- a/packages/zarr-metadata/src/zarr_metadata/typed_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/typed_json.py @@ -74,9 +74,7 @@ as a JSON Schema. `check` supports only annotations that describe JSON shapes: `int`, -`float` for any number, `bool`, `str`, `None`, `JSONValue`, -`UserJSONValue` (a `JSONValue` whose numbers may also be non-finite, for -user data such as attributes), a `Literal`, +`float` for any number, `bool`, `str`, `None`, `JSONValue`, a `Literal`, `tuple[T, ...]` and `tuple[T1, T2]`, a union, a TypedDict, `Mapping[str, V]`, a `NewType` and a type alias. A TypedDict that contains anything else raises `TypeError`, naming the member and the @@ -91,7 +89,7 @@ `typing_extensions.TypedDict` records the bases on every version. """ -from zarr_metadata._common import JSONValue, UserJSONValue +from zarr_metadata._common import JSONValue from zarr_metadata._typed_json import ( Loc, check, @@ -100,6 +98,5 @@ __all__ = [ "JSONValue", "Loc", - "UserJSONValue", "check", ] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py index d5a3e5b3f9..6133c16e61 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py @@ -2,13 +2,14 @@ from __future__ import annotations +import dataclasses import math import struct from dataclasses import dataclass from typing import TYPE_CHECKING, Final from zarr_metadata._json import ValidationProblem -from zarr_metadata.definition._definition import ConstantFillValue +from zarr_metadata.definition._definition import ConstantFillValue, non_finite_fill_value from zarr_metadata.v2._definition import ZarrV2DataTypeDefinition from zarr_metadata.v2._types.data_type import ( ZarrV2ByteOrder, @@ -51,6 +52,24 @@ def __call__( ) +def _float_fill_value_rules( + configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2FloatFillValue +) -> Iterator[ValidationProblem]: + """The rule for a float fill value: a number that is not finite is written by its name.""" + yield from non_finite_fill_value(value) + + +def _complex_fill_value_rules( + configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2ComplexFillValue +) -> Iterator[ValidationProblem]: + """The rule for a complex fill value: a component that is a number that is not finite is written by its name, as a float fill value is.""" + if value is None: + return + for index, part in enumerate(value): + for found in non_finite_fill_value(part): + yield dataclasses.replace(found, loc=(index, *found.loc)) + + def _float_canonical( configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2FloatFillValue ) -> ZarrV2FloatFillValue: @@ -132,6 +151,7 @@ def _complex_canonical( configuration=ZarrV2ScalarConfiguration, rules=sized((2, 4, 8), frozenset()), fill_value=ZarrV2FloatFillValue, + fill_value_rules=_float_fill_value_rules, fill_value_default=ConstantFillValue(0.0), fill_value_canonical=_float_canonical, ) @@ -142,6 +162,7 @@ def _complex_canonical( configuration=ZarrV2ScalarConfiguration, rules=sized((8, 16), frozenset()), fill_value=ZarrV2ComplexFillValue, + fill_value_rules=_complex_fill_value_rules, fill_value_default=ConstantFillValue((0.0, 0.0)), fill_value_canonical=_complex_canonical, ) diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_common.py b/packages/zarr-metadata/src/zarr_metadata/v3/_common.py index 74bf40b11d..d87233e9ac 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_common.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_common.py @@ -13,7 +13,7 @@ from typing_extensions import TypeAliasType, TypeIs -from zarr_metadata._common import UserJSONValue, ZarrV3NamedConfigJSON +from zarr_metadata._common import JSONValue, ZarrV3NamedConfigJSON from zarr_metadata._hierarchy import NodeType ZarrV3NodeType = NodeType @@ -34,11 +34,10 @@ def is_zarr_v3_node_type(value: object) -> TypeIs[ZarrV3NodeType]: return value in ZARR_V3_NODE_TYPE -ZarrV3ExtensionField: TypeAlias = UserJSONValue +ZarrV3ExtensionField: TypeAlias = JSONValue """The JSON value of an unknown top-level v3 metadata field. -A field nothing in scope claims is not interpreted, so, like attributes, -its numbers may also be `NaN`, `Infinity` or `-Infinity`. A definition that +A field nothing in scope claims is not interpreted. A definition that claims the field decides what it holds. An object carrying the literal member `must_understand: false` may be ignored. diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py index 6552581801..ca5ae05908 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py @@ -36,7 +36,6 @@ is_object, is_tuple, refine_json, - refine_user_data, with_input, ) from zarr_metadata._sentinel import UNSET @@ -520,12 +519,6 @@ class ExtraFieldDefinition(Definition[C]): lists it in `must_understand_fields` unless it says `"must_understand": false`. - A number that is not finite may stand only where the configuration's - annotation is `UserJSONValue`, as a node's attributes are: consolidated - metadata holds node documents, whose attributes may hold `NaN`, - `Infinity` and `-Infinity`. A member that nothing claims is not read, - so like attributes it may hold any number. - The spec lets every extension field carry `"must_understand": false`, which tells a reader that does not understand the member that it may ignore it. So the configuration declares `must_understand`, and a @@ -599,17 +592,16 @@ def _envelope_problems(cls, value: object, loc: Loc = ()) -> Problems: def _refined( cls, data: object, loc: Loc, definition: Definition[Any] | None ) -> tuple[JSONValue | UNSET, Problems]: - # The member's value is at the member's location, `loc`, and is - # refined as user data: the checks that read it decide what it may - # hold. A claimed member's value must be an object, or no + # The member's value is at the member's location, `loc`: the + # checks that read it decide what it may hold. A claimed member's value must be an object, or no # definition can read it. name = cls._named_configuration(data)[0] if name is None or not is_object(data): - refined, found = refine_user_data(data, loc) + refined, found = refine_json(data, loc) return (UNSET if len(found) != 0 else refined), () if definition is not None and not is_object(data[name]): return UNSET, (ValidationProblem(loc, "expected an object", "invalid_type"),) - value, found = refine_user_data(data[name], loc) + value, found = refine_json(data[name], loc) return (UNSET if len(found) != 0 else {name: value}), () @classmethod @@ -618,14 +610,14 @@ def _not_json(cls, data: object, loc: Loc) -> Problems: # location. name = cls._named_configuration(data)[0] if name is None or not is_object(data): - return refine_user_data(data, loc)[1] - return refine_user_data(data[name], loc)[1] + return refine_json(data, loc)[1] + return refine_json(data[name], loc)[1] @classmethod def _unread(cls, data: object, json: JSONValue | UNSET, loc: Loc) -> Problems: - # A member nothing claims is user data, like attributes: it need - # only be JSON, with any number, which `_refined` found it is - # unless `json` is `UNSET`. + # A member nothing claims is not interpreted, like attributes: it + # need only be JSON, which `_refined` found it is unless `json` is + # `UNSET`. if json is not UNSET: return () return cls._not_json(data, loc) diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_types/consolidated.py b/packages/zarr-metadata/src/zarr_metadata/v3/_types/consolidated.py index e321f48fec..ede8c7639e 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_types/consolidated.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_types/consolidated.py @@ -10,7 +10,7 @@ from typing_extensions import TypedDict -from zarr_metadata._common import UserJSONValue +from zarr_metadata._common import JSONValue from zarr_metadata.v3.array import ZarrV3ArrayMetadataJSON from zarr_metadata.v3.group import ZarrV3GroupMetadataJSON @@ -23,9 +23,7 @@ class ZarrV3ConsolidatedMetadataEnvelopeJSON(TypedDict, closed=True): reasons, and fixes its envelope: `kind` is `"inline"`, `must_understand` is false, and `metadata` is an object. The spec leaves the entries of `metadata` to the reference implementation, so - here they are any JSON, as user data: the attributes of a listed - document may hold `NaN`, `Infinity` and `-Infinity`. - `ZarrV3ConsolidatedMetadataJSON` types the + here they are any JSON. `ZarrV3ConsolidatedMetadataJSON` types the entries as the reference implementation writes them: an array or group document at each path. @@ -36,7 +34,7 @@ class ZarrV3ConsolidatedMetadataEnvelopeJSON(TypedDict, closed=True): """How the entries are carried, `"inline"`: in the group's own document.""" must_understand: Literal[False] """Always `false`: a reader that does not recognize consolidated metadata may ignore it.""" - metadata: Mapping[str, UserJSONValue] + metadata: Mapping[str, JSONValue] """The entries, by each node's path from the group, as any JSON.""" diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/array.py b/packages/zarr-metadata/src/zarr_metadata/v3/array.py index b5c38d26df..ab0f732162 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/array.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/array.py @@ -6,7 +6,7 @@ from annotated_types import Ge, MinLen from typing_extensions import TypedDict -from zarr_metadata._common import JSONValue, UserJSONValue +from zarr_metadata._common import JSONValue from zarr_metadata.v3._common import ( ZarrV3ChunkGridDeclaration, ZarrV3ChunkKeyEncodingDeclaration, @@ -54,7 +54,7 @@ class ZarrV3ArrayMetadataJSON(TypedDict, extra_items=ZarrV3ExtensionField): then zero or more bytes -> bytes codecs, so the list is never empty (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/core/index.rst#L974-L983). """ - attributes: NotRequired[Mapping[str, UserJSONValue]] + attributes: NotRequired[Mapping[str, JSONValue]] """User attributes: arbitrary JSON values by string key, whose numbers may also be `NaN`, `Infinity` or `-Infinity`, as zarr-python writes them.""" storage_transformers: NotRequired[tuple[ZarrV3StorageTransformerDeclaration, ...]] """The storage transformers between the array and its store. diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py b/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py index 196f549e46..91c2a454a4 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py @@ -28,7 +28,7 @@ configuration=ZarrV3ConsolidatedMetadataEnvelopeJSON, ) ) -"""A group's `consolidated_metadata` member, read as the envelope the core spec fixes. The documents it lists are not read: its configuration types them as `UserJSONValue`, since they may hold the non-finite numbers that node attributes may, and `ZarrV3ConsolidatedMetadata` reads them.""" +"""A group's `consolidated_metadata` member, read as the envelope the core spec fixes. The documents it lists are not read here: its configuration types them as `JSONValue`, and `ZarrV3ConsolidatedMetadata` reads them.""" __all__ = [ 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 c291eb2a52..8d7c784c4b 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 @@ -20,7 +20,7 @@ from zarr_metadata._common import EmptyConfiguration, JSONValue from zarr_metadata._json import ValidationProblem, choices, shown -from zarr_metadata.definition._definition import Nested +from zarr_metadata.definition._definition import Nested, non_finite_fill_value from zarr_metadata.v3._types.data_type import FLOAT_SPECIAL_FILL_VALUES @@ -29,7 +29,8 @@ def float_fill_value_rules( ) -> Callable[[EmptyConfiguration, Nested, float | str], Iterator[ValidationProblem]]: """Return the fill value rules of the floating-point type `name`. `hex_form` accepts its hex strings. - A number may have any value, because a reader rounds it. A string + A finite number may have any value, because a reader rounds it. A + number that is not finite is written by its name. A string must be one of the named values, or a hex string of the type's own width. The type-checked shape accepts any string here, so `hex_form` raises `ValueError` for a string that is not a valid hex string. @@ -47,7 +48,10 @@ class _FloatFillValue: def __call__( self, configuration: EmptyConfiguration, nested: Nested, value: float | str ) -> Iterator[ValidationProblem]: - if not isinstance(value, str) or value in FLOAT_SPECIAL_FILL_VALUES: + if not isinstance(value, str): + yield from non_finite_fill_value(value) + return + if value in FLOAT_SPECIAL_FILL_VALUES: return try: self.hex_form(value) diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/group.py b/packages/zarr-metadata/src/zarr_metadata/v3/group.py index 584564d1e8..235d2df41c 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/group.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/group.py @@ -8,7 +8,7 @@ from typing_extensions import TypedDict -from zarr_metadata._common import UserJSONValue +from zarr_metadata._common import JSONValue from zarr_metadata.v3._common import ZarrV3ExtensionField @@ -25,7 +25,7 @@ class ZarrV3GroupMetadataJSON(TypedDict, extra_items=ZarrV3ExtensionField): """The Zarr format version, `3`.""" node_type: Literal["group"] """The kind of node the document describes, `"group"`.""" - attributes: NotRequired[Mapping[str, UserJSONValue]] + attributes: NotRequired[Mapping[str, JSONValue]] """User attributes: arbitrary JSON values by string key, whose numbers may also be `NaN`, `Infinity` or `-Infinity`, as zarr-python writes them.""" diff --git a/packages/zarr-metadata/tests/model/test_array.py b/packages/zarr-metadata/tests/model/test_array.py index ad8cb99128..0399f013d7 100644 --- a/packages/zarr-metadata/tests/model/test_array.py +++ b/packages/zarr-metadata/tests/model/test_array.py @@ -1395,9 +1395,10 @@ def test_v2_from_json_nested_arrays_in_attributes_become_tuples() -> None: Expect(None, frozenset(), id="none"), Expect({"a": [1, {"b": None}], "c": "x"}, frozenset(), id="nested-containers"), Expect((1, 2, 3), frozenset(), id="tuple-array"), - Expect(float("nan"), frozenset({()}), id="nan"), - Expect(float("inf"), frozenset({()}), id="inf"), - Expect(float("-inf"), frozenset({()}), id="negative-inf"), + # Whether JSON text may hold a non-finite number is for the routines that + # read and write it. (NaN is left out: it does not equal itself.) + Expect(float("inf"), frozenset(), id="inf"), + Expect(float("-inf"), frozenset(), id="negative-inf"), Expect(object(), frozenset({()}), id="object"), Expect(b"abc", frozenset({()}), id="bytes"), Expect(bytearray(b"abc"), frozenset({()}), id="bytearray"), @@ -2027,19 +2028,23 @@ def test_array_v3_from_json_materializes_abstract_containers() -> None: def test_from_key_value_rejects_non_standard_json_constant() -> None: - """A JavaScript NaN constant outside the attributes is located, not decoded as a fill value.""" - doc = dict(ZarrV3ArrayMetadata.create_default().to_json()) + """A NaN constant, which `json.loads` reads, is not a float fill value: the spec writes it by its name.""" + doc = dict(ZarrV3ArrayMetadata.create_default(data_type="float32").to_json()) doc["fill_value"] = float("nan") raw = json.dumps(doc) - with pytest.raises(MetadataValidationError, match="fill_value: non-finite float nan"): + with pytest.raises( + MetadataValidationError, + match="fill_value: expected a non-finite fill value written by its name", + ): ZarrV3ArrayMetadata.from_key_value({"zarr.json": raw.encode()}) @pytest.mark.parametrize( ("members", "problems"), [ - ({"fill_value": math.nan}, [(("fill_value",), "invalid_value")]), + # A float's non-finite fill value is written by its name. + ({"data_type": "float32", "fill_value": math.nan}, [(("fill_value",), "invalid_value")]), # A fill value given, 0, is not a boolean. A data type requires a # fill value of that type. ({"data_type": "bool", "fill_value": 0}, [(("fill_value",), "invalid_type")]), @@ -2147,10 +2152,10 @@ def test_a_codec_that_is_not_json_is_placed_by_the_definition_that_claims_its_na """A codec whose configuration is not JSON takes the kind of the definition that claims its name, as a codec refused for a JSON configuration does. `gzip` is a bytes -> bytes codec, so the pipeline still lacks an array -> bytes codec.""" document = { **ZarrV3ArrayMetadata.create_default().to_json(), - "codecs": [{"name": "gzip", "configuration": {"level": math.nan}}], + "codecs": [{"name": "gzip", "configuration": {"level": b"5"}}], } assert [(p.loc, p.kind) for p in read_array_metadata_v3(document).problems] == [ - (("codecs", 0, "configuration", "level"), "invalid_value"), + (("codecs", 0, "configuration", "level"), "invalid_type"), (("codecs",), "invalid_value"), ] diff --git a/packages/zarr-metadata/tests/model/test_consolidating.py b/packages/zarr-metadata/tests/model/test_consolidating.py index 04e60cc1a4..771be191c9 100644 --- a/packages/zarr-metadata/tests/model/test_consolidating.py +++ b/packages/zarr-metadata/tests/model/test_consolidating.py @@ -98,7 +98,7 @@ def test_a_model_is_accepted_as_a_consolidated_entry_when_it_refines_into_the_sc assert held == _consolidated(context, a=child.to_json(), **written) group = ZarrV3GroupMetadata.create_default(context=context, consolidated_metadata=held) document = group.to_json() - assert is_canonical_json(document, finite=False) + assert is_canonical_json(document) assert read_group_metadata_v3(document).problems == () diff --git a/packages/zarr-metadata/tests/model/test_construction.py b/packages/zarr-metadata/tests/model/test_construction.py index 86fe6a8a57..b451f3d288 100644 --- a/packages/zarr-metadata/tests/model/test_construction.py +++ b/packages/zarr-metadata/tests/model/test_construction.py @@ -219,7 +219,7 @@ def counted( @pytest.mark.parametrize( ("model", "changes", "problems"), [ - (ARRAY, {"fill_value": math.nan}, [(("fill_value",), "invalid_value")]), + (ARRAY, {"fill_value": b"0"}, [(("fill_value",), "invalid_type")]), (ARRAY, {"dimension_names": ("x", "y")}, [(("dimension_names",), "invalid_value")]), # Both problems are reported: the grid and the names each cover one dimension. ( diff --git a/packages/zarr-metadata/tests/model/test_extension_points.py b/packages/zarr-metadata/tests/model/test_extension_points.py index fc2c871c9a..5ff5497234 100644 --- a/packages/zarr-metadata/tests/model/test_extension_points.py +++ b/packages/zarr-metadata/tests/model/test_extension_points.py @@ -10,7 +10,6 @@ from __future__ import annotations -import math from typing import TYPE_CHECKING, Any, cast import pytest @@ -197,17 +196,17 @@ def test_error_an_envelope_is_judged_once() -> None: def test_error_a_declaration_that_is_not_json_is_still_read() -> None: - # The NaN is reported where it sits, and the configuration next to it is - # still read, so its problem is reported too. + # The bytes are reported where they sit, and the configuration next to + # them is still read, so its problem is reported too. document = _document( codecs=[ BYTES, - {"name": "gzip", "configuration": {"level": 99}, "must_understand": math.nan}, + {"name": "gzip", "configuration": {"level": 99}, "must_understand": b"yes"}, ] ) assert [ (problem.loc, problem.kind) for problem in read_array_metadata_v3(document).problems ] == [ - (("codecs", 1, "must_understand"), "invalid_value"), + (("codecs", 1, "must_understand"), "invalid_type"), (("codecs", 1, "configuration", "level"), "invalid_value"), ] diff --git a/packages/zarr-metadata/tests/model/test_extra_fields.py b/packages/zarr-metadata/tests/model/test_extra_fields.py index 5c30c0bad5..f7437e4811 100644 --- a/packages/zarr-metadata/tests/model/test_extra_fields.py +++ b/packages/zarr-metadata/tests/model/test_extra_fields.py @@ -196,15 +196,6 @@ def test_error_a_claimed_extra_field_with_a_bad_configuration() -> None: ] -def test_error_a_non_finite_number_in_an_extra_field_that_holds_no_user_data() -> None: - """A number in a claimed extra field must be finite unless its configuration says `UserJSONValue` there, as `CONSOLIDATED_METADATA_EXTRA_FIELD`'s does for the documents it lists.""" - with pytest.raises(MetadataValidationError) as raised: - ZarrV3ArrayMetadata({**ARRAY, "acme.note": {"note": [math.nan]}}, context=CONTEXT) - assert [(p.loc, p.kind) for p in raised.value.problems] == [ - (("acme.note", "note", 0), "invalid_value") - ] - - @pytest.mark.parametrize( ("kind", "name"), [ diff --git a/packages/zarr-metadata/tests/model/test_refine_json.py b/packages/zarr-metadata/tests/model/test_refine_json.py index 1c98a1b8a1..f5a38bc341 100644 --- a/packages/zarr-metadata/tests/model/test_refine_json.py +++ b/packages/zarr-metadata/tests/model/test_refine_json.py @@ -5,19 +5,11 @@ import math from collections import OrderedDict, UserDict from types import MappingProxyType -from typing import TYPE_CHECKING, cast +from typing import cast import pytest -from zarr_metadata._json import JSON_DEPTH, refine_json, refine_user_data, shown - -if TYPE_CHECKING: - from collections.abc import Callable - - from zarr_metadata.problems import ValidationProblem - from zarr_metadata.typed_json import JSONValue - - _Refiner = Callable[[object], tuple[JSONValue | None, tuple[ValidationProblem, ...]]] +from zarr_metadata._json import JSON_DEPTH, refine_json, shown @pytest.mark.parametrize( @@ -32,29 +24,28 @@ ((1, 2), (1, 2)), ({"a": [1], "b": {"c": None}}, {"a": (1,), "b": {"c": None}}), (OrderedDict(k=[0]), {"k": (0,)}), + ({"range": [-math.inf, math.inf]}, {"range": (-math.inf, math.inf)}), + ], + ids=[ + "int", + "float", + "bool", + "str", + "null", + "nested-lists", + "tuple", + "object", + "any-mapping", + "non-finite", ], - ids=["int", "float", "bool", "str", "null", "nested-lists", "tuple", "object", "any-mapping"], ) def test_json_is_refined_to_tuples_and_dicts(value: object, refined: object) -> None: - # A single walk both normalizes and validates. + # A single walk both normalizes and validates. A float is JSON whatever + # its value: whether JSON text may hold it is for the routines that + # write it. assert refine_json(value) == (refined, ()) -def test_user_data_holds_non_finite_numbers() -> None: - # User data is JSON as Python's `json` module reads and writes it. The - # walk is the same as in `refine_json`, and a non-finite number stays a float. - assert refine_user_data({"range": [-math.inf, math.inf]}) == ( - {"range": (-math.inf, math.inf)}, - (), - ) - refined, problems = refine_user_data(math.nan) - assert problems == () - assert isinstance(refined, float) - assert math.isnan(refined) - - -# User data, like JSON, is refused at any position where it is not JSON. -@pytest.mark.parametrize("refine", [refine_json, refine_user_data], ids=["json", "user-data"]) @pytest.mark.parametrize( ("value", "loc"), # `bytes` is a sequence of integers, but it is not a JSON array. @@ -62,31 +53,19 @@ def test_user_data_holds_non_finite_numbers() -> None: ids=["object", "bytes"], ) def test_error_a_leaf_that_is_not_json_is_located( - refine: _Refiner, value: object, loc: tuple[str | int, ...] + value: object, loc: tuple[str | int, ...] ) -> None: - refined, problems = refine(value) + refined, problems = refine_json(value) assert refined is None assert [(problem.loc, problem.kind) for problem in problems] == [(loc, "invalid_type")] -@pytest.mark.parametrize("refine", [refine_json, refine_user_data], ids=["json", "user-data"]) -def test_error_a_non_string_key_is_located_at_its_object(refine: _Refiner) -> None: - refined, problems = refine([1, [2, {3: 4}]]) +def test_error_a_non_string_key_is_located_at_its_object() -> None: + refined, problems = refine_json([1, [2, {3: 4}]]) assert refined is None assert [(problem.loc, problem.kind) for problem in problems] == [((1, 1), "invalid_type")] -@pytest.mark.parametrize( - ("value", "loc"), - [({"x": math.inf}, ("x",)), ({"x": [math.nan]}, ("x", 0))], - ids=["infinite", "nan-in-array"], -) -def test_error_a_non_finite_number_is_not_json(value: object, loc: tuple[str | int, ...]) -> None: - refined, problems = refine_json(value) - assert refined is None - assert [(problem.loc, problem.kind) for problem in problems] == [(loc, "invalid_value")] - - def test_error_every_leaf_that_is_not_json_is_reported() -> None: refined, problems = refine_json({"a": object(), "b": [1, object()]}) assert refined is None @@ -239,16 +218,16 @@ class Mapped(dict[str, object]): {**held, "a": Listed(cast("list[object]", held["a"]))}, ): assert refine_json(other) == expected - bad: dict[str, object] = {"a": [1, {"b": math.nan}], "c": {1, 2}} + bad: dict[str, object] = {"a": [1, {"b": b"x"}], "c": {1, 2}} for other in ( bad, MappingProxyType(bad), Mapped(bad), - {**bad, "a": Listed([1, {"b": math.nan}])}, + {**bad, "a": Listed([1, {"b": b"x"}])}, ): refined, problems = refine_json(other) assert refined is None assert [(p.loc, p.kind) for p in problems] == [ - (("a", 1, "b"), "invalid_value"), + (("a", 1, "b"), "invalid_type"), (("c",), "invalid_type"), ] diff --git a/packages/zarr-metadata/tests/model/test_store_json.py b/packages/zarr-metadata/tests/model/test_store_json.py index 7507a24bae..4d65528ec1 100644 --- a/packages/zarr-metadata/tests/model/test_store_json.py +++ b/packages/zarr-metadata/tests/model/test_store_json.py @@ -236,27 +236,20 @@ def test_a_sequence_is_written_as_an_array() -> None: _V2_ARRAY: dict[str, object] = dict(ZarrV2ArrayMetadata.create_default().to_json()) -# Each case: a reader, a store it refuses, and the location of the non-finite number. +_FLOAT_ARRAY: dict[str, object] = {**_ARRAY, "data_type": "float32"} +_V2_FLOAT_ARRAY: dict[str, object] = {**_V2_ARRAY, "dtype": " None: "node_type": "group", "consolidated_metadata": { **_INLINE, - "metadata": {"a": {**_ARRAY, "fill_value": math.nan}}, + "metadata": {"a": {**_FLOAT_ARRAY, "fill_value": math.nan}}, }, }, ), ("metadata", "a", "fill_value"), ), - # A v2 array's attributes live in `.zattrs`. Its `.zarray` must be RFC 8259 - # JSON throughout, and zarr-python 3.0 once wrote a bare `NaN` there. + # zarr-python 3.0 once wrote a bare `NaN` fill value in a `.zarray`. "zarray": ( ZarrV2ArrayMetadata.from_key_value, - _stored(".zarray", {**_V2_ARRAY, "fill_value": math.nan}), + _stored(".zarray", {**_V2_FLOAT_ARRAY, "fill_value": math.nan}), (".zarray", "fill_value"), ), # Each `.zmetadata` entry is validated as the document type its key names. @@ -290,7 +282,7 @@ def test_a_sequence_is_written_as_an_array() -> None: "zarr_consolidated_format": 1, "metadata": { "a/.zattrs": {"x": math.nan}, - "a/.zarray": {**_V2_ARRAY, "fill_value": math.nan}, + "a/.zarray": {**_V2_FLOAT_ARRAY, "fill_value": math.nan}, }, }, ), @@ -300,13 +292,14 @@ def test_a_sequence_is_written_as_an_array() -> None: @pytest.mark.parametrize(("read", "store", "loc"), list(_REFUSED.values()), ids=list(_REFUSED)) -def test_error_a_non_finite_number_outside_attributes_is_located_when_read( +def test_error_a_non_finite_float_fill_value_is_located_when_read( read: Callable[[Mapping[str, bytes]], object], store: Mapping[str, bytes], loc: tuple[str | int, ...], ) -> None: - # Python's decoder reads a bare `NaN` as a float. Where the spec - # interprets a value, the document's validator reports its location. + # Python's decoder reads a bare `NaN` as a float, and a number of any + # value is JSON. The spec writes a float's non-finite fill value by its + # name, so the reader reports the number where it sits. with pytest.raises(MetadataValidationError) as raised: read(store) assert [(problem.loc, problem.kind) for problem in raised.value.problems] == [ @@ -319,7 +312,7 @@ def test_error_a_non_finite_number_outside_attributes_is_located_when_read( [ ( lambda: ZarrV3ArrayMetadata.create_default( - fill_value=math.nan, attributes={"x": math.nan} + data_type="float32", fill_value=math.nan, attributes={"x": math.nan} ), [(("fill_value",), "invalid_value")], ), diff --git a/packages/zarr-metadata/tests/model/test_typed_document.py b/packages/zarr-metadata/tests/model/test_typed_document.py index 392f1576c3..581945c887 100644 --- a/packages/zarr-metadata/tests/model/test_typed_document.py +++ b/packages/zarr-metadata/tests/model/test_typed_document.py @@ -9,7 +9,7 @@ import pytest from typing_extensions import TypedDict -from zarr_metadata._common import UserJSONValue +from zarr_metadata._common import JSONValue from zarr_metadata._json import JSON_DEPTH from zarr_metadata.definition import AcceptedDeclaration, RefusedDeclaration, resolve from zarr_metadata.model import ( @@ -42,14 +42,14 @@ def _deep(levels: int) -> object: class _Note(TypedDict, closed=True): - note: UserJSONValue + note: JSONValue must_understand: bool class _Mix(TypedDict, closed=True): codec: ZarrV3CodecDeclaration scale: float - note: UserJSONValue + note: JSONValue must_understand: bool @@ -93,13 +93,13 @@ def _array(**members: object) -> dict[str, object]: ( _array( codecs=[ - {"name": "bytes", "configuration": {"endian": float("nan")}}, + {"name": "bytes", "configuration": {"endian": b"little"}}, {"name": "zstd", "configuration": {"level": _PAST_THE_LEVELS}}, ] ), CORE_CONTEXT, { - (("codecs", 0, "configuration", "endian"), "invalid_value"), + (("codecs", 0, "configuration", "endian"), "invalid_type"), (("codecs", 1, "configuration", "level", ...), "invalid_value"), }, ), @@ -118,8 +118,8 @@ def _array(**members: object) -> dict[str, object]: }, ), # A claimed extension field is refined by the definition that claims - # it: a number that is not finite is allowed where the definition - # allows one, and nesting past the levels is still a problem. + # it: nesting past the levels is a problem, and a number of any value + # is JSON. ( _array( **{"acme.note": {"note": [float("nan"), _PAST_THE_LEVELS], "must_understand": True}} @@ -132,9 +132,8 @@ def _array(**members: object) -> dict[str, object]: _NOTE_CONTEXT, set(), ), - # A number that is not finite may stand only where the configuration - # says `UserJSONValue`: not in a number, and not in a declaration it - # holds, which is reported where it is not JSON. + # A declaration the configuration holds is reported where it is not + # JSON. A number that is not finite is a number. ( _array(**{"acme.mix": _mix({"name": "bytes"}, 1.5)}), _NOTE_CONTEXT, @@ -144,23 +143,19 @@ def _array(**members: object) -> dict[str, object]: _array( **{ "acme.mix": _mix( - {"name": "bytes", "configuration": {"endian": math.nan}}, math.inf + {"name": "bytes", "configuration": {"endian": b"little"}}, math.inf ) } ), _NOTE_CONTEXT, - { - (("acme.mix", "codec", "configuration", "endian"), "invalid_value"), - (("acme.mix", "scale"), "invalid_value"), - }, + {(("acme.mix", "codec", "configuration", "endian"), "invalid_type")}, ), # A key the configuration does not declare is reported, and what it - # holds is still refined: no annotation says it may hold a number - # that is not finite. + # holds is still refined. ( - _array(**{"acme.note": {"note": 1, "must_understand": True, "x": math.nan}}), + _array(**{"acme.note": {"note": 1, "must_understand": True, "x": b"x"}}), _NOTE_CONTEXT, - {(("acme.note", "x"), "unknown_key"), (("acme.note", "x"), "invalid_value")}, + {(("acme.note", "x"), "unknown_key"), (("acme.note", "x"), "invalid_type")}, ), # A key that is not a string is reported by the configuration's # checker, and refuses the member. @@ -172,13 +167,13 @@ def _array(**members: object) -> dict[str, object]: ], ids=[ "non-json-codec", - "nan-and-deep-codecs", + "bytes-and-deep-codecs", "bad-level-and-deep", "claimed-deep", "claimed-nan", - "user-data-where-annotated", - "not-finite-elsewhere", - "not-finite-under-unknown-key", + "a-nested-declaration", + "not-json-in-a-nested-declaration", + "not-json-under-unknown-key", "non-string-key-in-a-member", ], ) @@ -211,11 +206,11 @@ def test_error_a_configuration_refuses_a_declaration_in_it_that_is_not_json() -> # reported where it is not. definition = ArrayExtraFieldDefinition(name="acme.mix", configuration=_Mix) configuration, problems = definition.read_configuration( - _mix({"name": "bytes", "configuration": {"endian": math.nan}}, 1.5) + _mix({"name": "bytes", "configuration": {"endian": b"little"}}, 1.5) ) assert configuration is None assert [(problem.loc, problem.kind) for problem in problems] == [ - (("codec", "configuration", "endian"), "invalid_value") + (("codec", "configuration", "endian"), "invalid_type") ] @@ -239,18 +234,18 @@ def test_a_declaration_without_a_configuration_reads_up_to_the_last_level( @pytest.mark.parametrize( ("extra", "expected"), [ - ({"foo": math.nan}, [(("foo",), "unknown_key"), (("foo",), "invalid_value")]), + ({"foo": math.nan}, [(("foo",), "unknown_key")]), ( - {"foo": math.nan, "bar": math.inf}, + {"foo": b"a", "bar": {1}}, [ (("foo",), "unknown_key"), - (("foo",), "invalid_value"), + (("foo",), "invalid_type"), (("bar",), "unknown_key"), - (("bar",), "invalid_value"), + (("bar",), "invalid_type"), ], ), ({"foo": _deep(JSON_DEPTH - 2)}, [(("foo",), "unknown_key")]), - ({"kind": math.inf}, [(("kind",), "invalid_value")]), + ({"kind": math.inf}, [(("kind",), "invalid_type")]), # What is not JSON does not keep either reader from reporting every # other problem. ( @@ -264,10 +259,10 @@ def test_a_declaration_without_a_configuration_reads_up_to_the_last_level( ), ], ids=[ - "nan", + "a-number-that-is-not-finite", "two-keys", "deepest", - "kind-not-finite", + "kind-a-number", "not-json-beside-a-wrong-value", "non-string-key", "past-the-levels", @@ -349,12 +344,12 @@ def test_error_a_codec_holding_a_codec_that_is_not_json_is_refused() -> None: "name": "sharding_indexed", "configuration": { "chunk_shape": [2], - "codecs": [{"name": "bytes", "configuration": {"endian": math.nan}}], - "index_codecs": [{"name": "bytes"}], + "codecs": [{"name": "bytes", "configuration": {"endian": b"little"}}], + "index_codecs": [{"name": "bytes", "configuration": {"endian": "little"}}], }, } resolved, problems = resolve(sharding, CodecDefinition, CORE_CONTEXT) assert isinstance(resolved, RefusedDeclaration) assert [(problem.loc, problem.kind) for problem in problems] == [ - (("configuration", "codecs", 0, "configuration", "endian"), "invalid_value") + (("configuration", "codecs", 0, "configuration", "endian"), "invalid_type") ] diff --git a/packages/zarr-metadata/tests/test_problem_data.py b/packages/zarr-metadata/tests/test_problem_data.py index 34d2d79799..ed1d480767 100644 --- a/packages/zarr-metadata/tests/test_problem_data.py +++ b/packages/zarr-metadata/tests/test_problem_data.py @@ -93,8 +93,8 @@ def test_a_problem_carries_what_was_found_and_what_was_expected( @pytest.mark.parametrize( "ctx", - [["ge", 0], {1: 0}, {"ge": {0}}, {"ge": math.nan}], - ids=["an-array", "a-key-that-is-not-a-string", "a-set", "nan"], + [["ge", 0], {1: 0}, {"ge": {0}}], + ids=["an-array", "a-key-that-is-not-a-string", "a-set"], ) def test_error_a_problem_refuses_a_ctx_that_is_not_an_object_of_json_values(ctx: object) -> None: with pytest.raises(TypeError, match="ctx is an object of JSON values"): @@ -228,7 +228,7 @@ def _raised(read: Callable[[], object]) -> Sequence[ValidationProblem]: ), 300, ), - (validate_json, {"a": [math.inf]}), + (validate_json, {"a": [b"x"]}), ( lambda value: resolve(value, CodecDefinition, CORE_AND_EXTENSIONS_CONTEXT)[1], {"name": 1, "configuration": {"a": [math.nan]}, "extra": [1]}, @@ -300,9 +300,7 @@ def test_every_problem_a_reader_finds_holds_what_the_value_handed_in_holds_there assert len(problems) != 0 for problem in problems: there = value_at(value, problem.loc) - assert problem.input is (there if is_canonical_json(there, finite=False) else UNSET), ( - problem - ) + assert problem.input is (there if is_canonical_json(there) else UNSET), problem if value is BAD_ARRAY: assert {problem.loc for problem in problems} >= BAD_ARRAY_LOCS diff --git a/packages/zarr-metadata/tests/test_public_api.py b/packages/zarr-metadata/tests/test_public_api.py index 71f7b8064e..4f69db7ca9 100644 --- a/packages/zarr-metadata/tests/test_public_api.py +++ b/packages/zarr-metadata/tests/test_public_api.py @@ -355,7 +355,6 @@ def test_all_is_grouped_and_unique() -> None: "JSONWriter", "JSONWriterSchema", "JSONWriterLike", - "UserJSONValue", # A pydantic field's scope, fixed: `Annotated[Model, InScope(CONTEXT)]`. "InScope", "MetadataValidationError", diff --git a/packages/zarr-metadata/tests/test_typed_json.py b/packages/zarr-metadata/tests/test_typed_json.py index 42f1696ca6..cb33581916 100644 --- a/packages/zarr-metadata/tests/test_typed_json.py +++ b/packages/zarr-metadata/tests/test_typed_json.py @@ -55,7 +55,6 @@ import zarr_metadata.definition import zarr_metadata.v2 import zarr_metadata.v3 -from zarr_metadata._common import UserJSONValue from zarr_metadata._json import JSON_DEPTH from zarr_metadata._typed_json import ( Parsed, @@ -228,8 +227,9 @@ def test_a_value_of_the_shape_reads_as_itself( (str | tuple[str, ...], UserList([Color.RED]), ("red",)), (Mapping[str, int], types.MappingProxyType({"a": Size.LARGE}), {"a": 3}), (JSONValue, {"a": UserList([Color.RED])}, {"a": ("red",)}), - (UserJSONValue, [math.inf], (math.inf,)), - (Mapping[str, UserJSONValue], {"a": math.nan}, {"a": math.nan}), + (JSONValue, [math.inf], (math.inf,)), + (Mapping[str, JSONValue], {"a": math.nan}, {"a": math.nan}), + (float, -math.inf, -math.inf), ], ids=[ "str-enum", @@ -241,16 +241,17 @@ def test_a_value_of_the_shape_reads_as_itself( "union", "mapping-proxy", "json", - "user-data", - "user-data-in-a-mapping", + "non-finite", + "non-finite-in-a-mapping", + "non-finite-number", ], ) def test_a_value_as_a_document_holds_it_reads_as_its_json( annotation: object, value: object, parsed: object ) -> None: # A parser refines what it reads: a value that stands for JSON reads as - # that JSON, and a number need not be finite where the annotation is - # `UserJSONValue`. + # that JSON. A number need not be finite: whether JSON text may hold it + # is for the routines that write it. typed, found = _read(annotation, value) assert found == () # Compared as JSON text, so that NaN equals itself and a type is checked. @@ -258,21 +259,6 @@ def test_a_value_as_a_document_holds_it_reads_as_its_json( assert type(typed) is type(parsed) -@pytest.mark.parametrize( - ("annotation", "value", "loc"), - [ - (float, math.nan, ()), - (JSONValue, {"a": math.inf}, ("a",)), - (tuple[float, ...], [1.0, math.nan], (1,)), - ], - ids=["float", "json", "sequence"], -) -def test_error_a_number_that_is_not_finite_is_not_json_where_the_annotation_says_json( - annotation: object, value: object, loc: Loc -) -> None: - assert _found(_read(annotation, value)) == [(loc, "invalid_value")] - - def test_error_an_array_past_the_levels_is_refused_where_it_sits() -> None: # Counted from the root: the location says how deep the value already is. deep = parser(tuple[int, ...], no_leaf)([1], (0,) * JSON_DEPTH) @@ -1907,15 +1893,11 @@ def test_error_check_names_what_no_parser_reads() -> None: @pytest.mark.parametrize( ("value", "loc", "kind"), [ - ({"level": math.nan}, ("level",), "invalid_value"), - ({"level": 1, "note": math.inf}, ("note",), "invalid_value"), ({"level": 1, 2: 3}, (), "invalid_type"), ({"level": 1, "note": {1}}, ("note",), "invalid_type"), ({"level": 1, "note": {"a": [{3: 1}]}}, ("note",), "invalid_type"), ], ids=[ - "nan", - "infinity", "a-key-that-is-not-a-string", "a-set", "nested-key-that-is-not-a-string", @@ -1938,15 +1920,13 @@ def test_error_check_locates_a_value_that_is_not_json( (object(), "invalid_type"), (b"x", "invalid_type"), ({1: 2}, "invalid_type"), - (math.nan, "invalid_value"), ], - ids=["object", "bytes", "non-string-key", "nan"], + ids=["object", "bytes", "non-string-key"], ) def test_error_check_refuses_a_value_that_is_not_json_under_an_undeclared_key( junk: object, kind: str ) -> None: - # The key is reported and left out, and what it holds is still checked: - # no annotation says it may hold a number that is not finite. + # The key is reported and left out, and what it holds is still checked. typed, problems = check({"level": 1, "junk": junk}, Options) assert typed is None assert [(problem.loc, problem.kind) for problem in problems] == [ diff --git a/packages/zarr-metadata/tests/v2/test_data_types.py b/packages/zarr-metadata/tests/v2/test_data_types.py index 8561553f63..c1d7f600d4 100644 --- a/packages/zarr-metadata/tests/v2/test_data_types.py +++ b/packages/zarr-metadata/tests/v2/test_data_types.py @@ -2,6 +2,7 @@ from __future__ import annotations +import math from typing import TYPE_CHECKING import pytest @@ -250,6 +251,10 @@ def test_every_family_has_a_default_fill_value_it_takes(dtype: object, default: (" ( None ): - # A non-finite number is user data, so the nested declaration is JSON and - # the stack's rule runs: it refuses the bytes codec beside it. The - # nested codec's kind refuses its level. + # A non-finite number is JSON, so the nested declaration is too, and the + # stack's rule runs: it refuses the bytes codec beside it. The nested + # codec's kind refuses its level, which is not an integer. unread = {"name": "gzip", "configuration": {"level": math.nan}} declaration = {"name": "acme.stack", "configuration": {"codecs": [unread, "bytes"]}} resolved, found = resolve(declaration, CodecDefinition, CONTEXT) assert isinstance(resolved, RefusedDeclaration) assert _locs(found) == [ (("configuration", "codecs", 1), "invalid_value"), - (("configuration", "codecs", 0, "configuration", "level"), "invalid_value"), + (("configuration", "codecs", 0, "configuration", "level"), "invalid_type"), ] @@ -1622,13 +1622,13 @@ def test_error_a_bad_name_is_a_problem_when_the_declaration_is_not_json_too() -> # On both paths the name is refused before any definition is consulted. # A declaration whose configuration is not JSON reports its name problem as # the JSON path does, and no definition is asked to claim it. - declaration = {"name": "Acme", "configuration": {"x": float("nan")}} + declaration = {"name": "Acme", "configuration": {"x": b"x"}} resolved, problems = resolve(declaration, CodecDefinition, CORE_CONTEXT) assert isinstance(resolved, RefusedDeclaration) assert resolved.definition is None assert [(p.loc, p.kind) for p in problems] == [ (("name",), "invalid_value"), - (("configuration", "x"), "invalid_value"), + (("configuration", "x"), "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 80ff3e2621..b0391ec3db 100644 --- a/packages/zarr-metadata/tests/v3/test_fill_values.py +++ b/packages/zarr-metadata/tests/v3/test_fill_values.py @@ -167,8 +167,8 @@ def test_error_a_fill_value_of_the_wrong_json_type( assert _problems(data_type, fill_value) == [((), "invalid_type")] -def test_error_a_fill_value_that_is_not_json() -> None: - # A float's NaN is written as the string "NaN"; the number NaN is not JSON. +def test_error_a_non_finite_float_fill_value_written_as_a_number() -> None: + # A float's NaN is written as the string "NaN", not as the number. assert _problems("float32", math.nan) == [((), "invalid_value")] From 56561b57151ab9733159e47762919558ccd4bb12 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 14:41:41 +0100 Subject: [PATCH 19/27] refactor(zarr-metadata): drop the purity gate a nested non-finite number needed `_pure` refused a declaration whose nested declaration held a non-finite number. A non-finite number is JSON now, and a nested declaration that is not JSON already leaves the declaration holding it without JSON, so it is refused through `json is UNSET`. Also from review round 4 of the rules gate: pin that a nested declaration whose configuration is not an object keeps its holder's rules from running, and say in the gate's comment and `_held`'s docstring that the rules see only nested declarations that are JSON. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../zarr_metadata/definition/_definition.py | 22 ++++++------------- .../tests/v3/test_definitions.py | 16 ++++++++++++++ 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index 1871aa418a..c943250f27 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -1884,12 +1884,12 @@ def _read( inside.extend(found_inside) inside.extend(_sized(placed, inner)) # The rules may look up a nested declaration by its name, so they run only - # when every nested declaration has a name. Any other problem with a nested - # declaration belongs to that declaration and is reported at its location, as with - # a document's declarations. The declaration is accepted only when what it - # holds is JSON, so that it writes JSON. + # when every nested declaration is JSON and has a name (`_named`). Any + # other problem with a nested declaration belongs to that declaration and + # is reported at its location, as with a document's declarations. A + # nested declaration that is not JSON leaves this one not JSON either + # (`json` is `UNSET`), so it is refused. sound = _usable(found) and all(_named(declaration) for declaration in nested) - pure = all(_pure(inner) for inner in within.values()) configuration = ( cast( "Mapping[str, JSONValue]", @@ -1904,7 +1904,7 @@ def _read( ruled(definition, lambda: definition.rules(read_only(configuration), within), at) ) placed = _in_document(kind, loc, given is not None, own) - if configuration is None or json is UNSET or not pure or not _usable(placed): + if configuration is None or json is UNSET or not _usable(placed): refused = RefusedDeclaration( json=json, name=name, read_as=kind, definition=definition, nested=within ) @@ -1958,19 +1958,11 @@ def _named(declaration: _NestedDeclaration) -> bool: def _held(inner: ResolvedDeclaration[Any]) -> JSONValue: - """A nested declaration as the configuration that holds it shows it to its rules: as a document writes it. A declaration that is not JSON is never shown to a rule (see `_named`), so it is held as None only to keep the configuration a JSON value.""" + """A nested declaration as the configuration that holds it shows it to its rules: as a document writes it. The rules run only when every nested declaration is JSON (see `_named`), so the None for one that is not is never shown to a rule: it is there only for the type.""" written = document_json(inner) return None if written is UNSET else written -def _pure(inner: ResolvedDeclaration[Any]) -> bool: - """Whether a nested declaration, as a document writes it, is JSON with every number finite, so the declaration that holds it can be accepted and write JSON. A declaration that was read is; one that was refused is checked, since it is kept as written.""" - if not isinstance(inner, RefusedDeclaration): - return True - written = inner.json - return written is not UNSET and len(refine_json(written, ())[1]) == 0 - - def _given( shape: type, given: Mapping[str, object] | None, at: Loc ) -> tuple[object, Problems, tuple[_NestedDeclaration, ...]]: diff --git a/packages/zarr-metadata/tests/v3/test_definitions.py b/packages/zarr-metadata/tests/v3/test_definitions.py index 333ad51780..df284f945b 100644 --- a/packages/zarr-metadata/tests/v3/test_definitions.py +++ b/packages/zarr-metadata/tests/v3/test_definitions.py @@ -980,6 +980,22 @@ def test_error_a_container_rule_is_asked_of_a_nested_declaration_holding_a_non_f ] +def test_error_a_container_rule_is_not_asked_of_a_nested_declaration_whose_configuration_is_not_an_object() -> ( + None +): + # The stack's rule reads each nested declaration's name and + # configuration, so a nested declaration whose configuration is not an + # object keeps the rule from running: the bytes codec beside it is not + # reported. + declaration = { + "name": "acme.stack", + "configuration": {"codecs": [{"name": "gzip", "configuration": 5}, "bytes"]}, + } + resolved, found = resolve(declaration, CodecDefinition, CONTEXT) + assert isinstance(resolved, RefusedDeclaration) + assert _locs(found) == [(("configuration", "codecs", 0, "configuration"), "invalid_type")] + + def test_error_a_container_rule_is_not_asked_of_a_malformed_nested_declaration() -> None: # The stack's rule reads each nested declaration's name. A nested declaration with no # name is reported at its location, and the rule does not run, as it From 5d23015cbd2c46cfd20c0a849ef54ac20e85ad00 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 14:51:18 +0100 Subject: [PATCH 20/27] docs(zarr-metadata): describe where a non-finite number may stand now that JSON allows it Review round 1 of the non-finite change found stale text and test gaps: - docs/validation-rules.md still said `check` rejects a non-finite number everywhere. It now says a number may be non-finite anywhere except as a float fill value, and that a fill value of a data type nothing reads is not interpreted. The changelog fragment says so too. - The repair TypedDicts' docstrings no longer call a bare `NaN` "not JSON", or give `check` as the reason the fill value is not a member. - The message no longer says "fill value", since scale_offset and cast_value spell their scalars the same way. - The kept rule is pinned for float16, float64, both complex types and a struct float field, and an unread data type's fill value is pinned as free to hold any number. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/changes/493.feature.md | 2 +- .../zarr-metadata/docs/validation-rules.md | 25 +++++++++--------- .../zarr_metadata/definition/_definition.py | 2 +- .../src/zarr_metadata/model/_repair.py | 10 +++---- .../src/zarr_metadata/testing/_document.py | 2 +- .../zarr-metadata/tests/model/test_array.py | 2 +- .../zarr-metadata/tests/model/test_repair.py | 2 +- .../tests/v3/test_definitions.py | 9 +++---- .../tests/v3/test_fill_values.py | 26 ++++++++++++++++--- 9 files changed, 50 insertions(+), 30 deletions(-) diff --git a/packages/zarr-metadata/changes/493.feature.md b/packages/zarr-metadata/changes/493.feature.md index 7c15779527..f6f8eccd1f 100644 --- a/packages/zarr-metadata/changes/493.feature.md +++ b/packages/zarr-metadata/changes/493.feature.md @@ -1 +1 @@ -Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite (`NaN`, `Infinity`, `-Infinity`, which Python's `json` module reads and writes) is now JSON everywhere: whether a document may hold one is left to the routines that read and write its text. A float's non-finite fill value must still be written by its name, as each spec says, in v2 as in v3. `refine_user_data`, `UserJSONValue` and `ExtraFieldDefinition`'s `finite` are removed. A value that is not JSON no longer stops a declaration's own checks, so the other problems in it are reported; a declaration that holds one is still refused. `typed_json.check` returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. +Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite (`NaN`, `Infinity`, `-Infinity`, which Python's `json` module reads and writes) is now JSON everywhere: whether a document may hold one is left to the routines that read and write its text. A float's non-finite fill value, or a complex component, must still be written by its name, as each spec says, in v2 as in v3; a fill value of a data type nothing in scope reads is not interpreted, so it may hold one. `refine_user_data`, `UserJSONValue` and `ExtraFieldDefinition`'s `finite` are removed. A value that is not JSON no longer stops a declaration's own checks, so the other problems in it are reported; a declaration that holds one is still refused. `typed_json.check` returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. diff --git a/packages/zarr-metadata/docs/validation-rules.md b/packages/zarr-metadata/docs/validation-rules.md index b1b17d3eb2..2be74ad7a1 100644 --- a/packages/zarr-metadata/docs/validation-rules.md +++ b/packages/zarr-metadata/docs/validation-rules.md @@ -67,18 +67,19 @@ whether a fill value survives a `cast_value` round trip. The spec leaves some choices open, or answers them in two ways. Here is what the package does. -**`attributes` may hold `NaN`, `Infinity` and `-Infinity`.** - -- The spec - [does not interpret attributes](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#attributes). -- zarr-python and xarray write these numbers there, for example as a CF - `_FillValue`. -- The models read them. `to_key_value` writes them back as bare tokens, - which a strict JSON parser rejects. -- The same goes for a member the spec does not define, when no definition - in the context claims it. Nothing reads it, so it is kept as written. -- `check`, from `zarr_metadata.typed_json`, rejects a non-finite number - anywhere, including in attributes. +**A number may be `NaN`, `Infinity` or `-Infinity`.** + +- Python's `json` module reads and writes these numbers, and zarr-python + and xarray write them in attributes, for example as a CF `_FillValue`. + Whether a document may hold them is left to the routines that read and + write its text. +- The readers, `check` from `zarr_metadata.typed_json`, and the models + accept them wherever a number may stand. `to_key_value` writes them + back as bare tokens, which a strict JSON parser rejects. +- One exception: a float fill value, or a complex fill value component, + that is a non-finite number is refused, because both specs write those + values by name. A fill value of a data type that nothing in the context + reads is not interpreted, so it may hold any number. **A reader walks at most 256 levels of nesting.** diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index c943250f27..6e8185044c 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -152,7 +152,7 @@ def non_finite_fill_value(value: object) -> tuple[ValidationProblem, ...]: return ( ValidationProblem( (), - f"expected a non-finite fill value written by its name, {name!r}, got the number {name}", + f"expected a non-finite value written by its name, {name!r}, got the number {name}", "invalid_value", ), ) diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py index 78511c26d5..c43976d84d 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py @@ -124,7 +124,7 @@ class ZarrV3NonFiniteFillValueArrayMetadataJSON(TypedDict): zarr-python 3.0.0 to 3.0.6 wrote the fill value of a float64 array, in the documents a group's consolidated metadata lists, as a bare `NaN`, - `Infinity` or `-Infinity`, which is not JSON. The spec writes these as + `Infinity` or `-Infinity`. The spec writes these as the strings `"NaN"`, `"Infinity"` and `"-Infinity"`. The repair writes each such fill value, or complex fill value component, of a float or complex data type by its name. @@ -360,13 +360,13 @@ class ZarrV2NonFiniteFillValueArrayMetadataJSON(TypedDict): zarr-python 3.0.0 to 3.0.6 wrote a non-finite fill value of a float array as a bare token, `"fill_value": NaN`, and each non-finite - component of a complex one the same way, `[NaN, Infinity]`. Neither - is JSON. The v2 spec spells these values as strings, `"NaN"`, + component of a complex one the same way, `[NaN, Infinity]`. The v2 + spec spells these values as strings, `"NaN"`, `"Infinity"` and `"-Infinity"` (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L178-L190), and so does zarr-python since 3.0.7. Python's `json` module reads the - tokens as floats, which `check` refuses, so the fill value is not a - member here: the repair reads a float, or a pair for a complex dtype. + tokens as floats. The fill value is not a member here, since it is a + float, or a pair for a complex dtype, and the repair reads it itself. """ zarr_format: Literal[2] diff --git a/packages/zarr-metadata/src/zarr_metadata/testing/_document.py b/packages/zarr-metadata/src/zarr_metadata/testing/_document.py index 16098f2a97..3e061b20a4 100644 --- a/packages/zarr-metadata/src/zarr_metadata/testing/_document.py +++ b/packages/zarr-metadata/src/zarr_metadata/testing/_document.py @@ -78,7 +78,7 @@ ), max_leaves=8, ) -"""JSON values, with JSON arrays as tuples. Only finite numbers: JSON has no others.""" +"""JSON values, with JSON arrays as tuples. Only finite numbers, so a drawn value is JSON to every reader.""" _ATTRIBUTES: Final = st.dictionaries(_TEXT, _JSON, max_size=_MAX_MEMBERS) diff --git a/packages/zarr-metadata/tests/model/test_array.py b/packages/zarr-metadata/tests/model/test_array.py index 0399f013d7..d08c273782 100644 --- a/packages/zarr-metadata/tests/model/test_array.py +++ b/packages/zarr-metadata/tests/model/test_array.py @@ -2035,7 +2035,7 @@ def test_from_key_value_rejects_non_standard_json_constant() -> None: with pytest.raises( MetadataValidationError, - match="fill_value: expected a non-finite fill value written by its name", + match="fill_value: expected a non-finite value written by its name", ): ZarrV3ArrayMetadata.from_key_value({"zarr.json": raw.encode()}) diff --git a/packages/zarr-metadata/tests/model/test_repair.py b/packages/zarr-metadata/tests/model/test_repair.py index 18d7639040..ebaf90200a 100644 --- a/packages/zarr-metadata/tests/model/test_repair.py +++ b/packages/zarr-metadata/tests/model/test_repair.py @@ -292,7 +292,7 @@ def _with_fill(zarray: dict[str, Any], fill_value: object) -> dict[str, object]: def test_repair_v2_node_writes_a_bare_non_finite_fill_value_by_name( files: dict[str, object], repaired: object, repairs: list[tuple[tuple[str | int, ...], str]] ) -> None: - """zarr-python 3.0.0 to 3.0.6 wrote a non-finite fill value of a float or complex `.zarray` as a bare token, `NaN`, which is not JSON. Python's `json` module reads it as a float. `repair_node_metadata_v2` writes each one as the string the v2 spec uses, and reports its location. Anything else is left unchanged, and the input files are not modified.""" + """zarr-python 3.0.0 to 3.0.6 wrote a non-finite fill value of a float or complex `.zarray` as a bare token, `NaN`. Python's `json` module reads it as a float. `repair_node_metadata_v2` writes each one as the string the v2 spec uses, and reports its location. Anything else is left unchanged, and the input files are not modified.""" before = copy.deepcopy(files) document, made = repair_node_metadata_v2(files) # `==` cannot compare NaN, which is never equal to itself, so compare the JSON text. diff --git a/packages/zarr-metadata/tests/v3/test_definitions.py b/packages/zarr-metadata/tests/v3/test_definitions.py index df284f945b..3dc2f14ba2 100644 --- a/packages/zarr-metadata/tests/v3/test_definitions.py +++ b/packages/zarr-metadata/tests/v3/test_definitions.py @@ -861,12 +861,11 @@ def test_error_null_is_not_a_declaration() -> None: @pytest.mark.parametrize("level", [math.nan, b"9"], ids=["not-finite", "bytes"]) -def test_error_a_value_that_is_not_json(level: object) -> None: +def test_error_a_level_gzip_does_not_read(level: object) -> None: # Its name still identifies the definition that claims it, which - # reports where the value is not JSON. A number that is not finite is - # user data, so the refusal holds the declaration as written; anything - # else that is not JSON is stored as `UNSET`, because no document can - # hold it. + # reports the level. A number that is not finite is JSON, so the + # refusal holds the declaration as written; a value that is not JSON + # is stored as `UNSET`, because no document can hold it. resolved, found = resolve( {"name": "gzip", "configuration": {"level": level}}, CodecDefinition, CONTEXT ) diff --git a/packages/zarr-metadata/tests/v3/test_fill_values.py b/packages/zarr-metadata/tests/v3/test_fill_values.py index b0391ec3db..08b07f82ec 100644 --- a/packages/zarr-metadata/tests/v3/test_fill_values.py +++ b/packages/zarr-metadata/tests/v3/test_fill_values.py @@ -167,9 +167,29 @@ def test_error_a_fill_value_of_the_wrong_json_type( assert _problems(data_type, fill_value) == [((), "invalid_type")] -def test_error_a_non_finite_float_fill_value_written_as_a_number() -> None: - # A float's NaN is written as the string "NaN", not as the number. - assert _problems("float32", math.nan) == [((), "invalid_value")] +@pytest.mark.parametrize( + ("data_type", "fill_value", "at"), + [ + ("float16", -math.inf, ()), + ("float32", math.nan, ()), + ("float64", math.inf, ()), + ("complex64", [0.0, math.nan], (1,)), + ("complex128", [math.inf, 0.0], (0,)), + (STRUCT, {"a": 0, "b": math.nan}, ("b",)), + ], +) +def test_error_a_non_finite_float_fill_value_written_as_a_number( + data_type: JSONValue, fill_value: object, at: tuple[str | int, ...] +) -> None: + # A float's NaN is written as the string "NaN", not as the number, and + # so is each component of a complex value and each float field. + assert _problems(data_type, fill_value) == [(at, "invalid_value")] + + +def test_a_fill_value_of_a_data_type_nothing_reads_may_be_any_number() -> None: + # Nothing interprets it, so a non-finite number is as good as any JSON. + resolved, _ = resolve("acme.unread", DataTypeDefinition, CORE_AND_EXTENSIONS_CONTEXT) + assert fill_value_problems(resolved, [math.nan, math.inf]) == () @pytest.mark.parametrize( From c7f34fa4dcd0126e8aeff8558f48b00f9aaf592e Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 14:59:15 +0100 Subject: [PATCH 21/27] docs(zarr-metadata): say a non-finite number may stand anywhere a number may Address NaN review round 1 (crash lens): the pydantic warning, the writer and to_key_value docs no longer say non-finite numbers are kept to attributes; the definition docs warn that an unbounded float may be non-finite; the removals move to their own changelog fragment. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/changes/493.feature.md | 2 +- packages/zarr-metadata/changes/493.removal.md | 1 + .../src/zarr_metadata/definition/__init__.py | 4 +++- .../zarr-metadata/src/zarr_metadata/model/_array_v3.py | 5 ++--- .../zarr-metadata/src/zarr_metadata/model/_group_v3.py | 6 ++---- .../zarr-metadata/src/zarr_metadata/model/_json_writer.py | 5 ++--- packages/zarr-metadata/src/zarr_metadata/pydantic.py | 8 +++++--- packages/zarr-metadata/src/zarr_metadata/typed_json.py | 2 +- 8 files changed, 17 insertions(+), 16 deletions(-) create mode 100644 packages/zarr-metadata/changes/493.removal.md diff --git a/packages/zarr-metadata/changes/493.feature.md b/packages/zarr-metadata/changes/493.feature.md index f6f8eccd1f..48569e4631 100644 --- a/packages/zarr-metadata/changes/493.feature.md +++ b/packages/zarr-metadata/changes/493.feature.md @@ -1 +1 @@ -Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite (`NaN`, `Infinity`, `-Infinity`, which Python's `json` module reads and writes) is now JSON everywhere: whether a document may hold one is left to the routines that read and write its text. A float's non-finite fill value, or a complex component, must still be written by its name, as each spec says, in v2 as in v3; a fill value of a data type nothing in scope reads is not interpreted, so it may hold one. `refine_user_data`, `UserJSONValue` and `ExtraFieldDefinition`'s `finite` are removed. A value that is not JSON no longer stops a declaration's own checks, so the other problems in it are reported; a declaration that holds one is still refused. `typed_json.check` returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. +Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite (`NaN`, `Infinity`, `-Infinity`, which Python's `json` module reads and writes) is now JSON everywhere: whether a document may hold one is left to the routines that read and write its text. A float's non-finite fill value, or a complex component, must still be written by its name, as each spec says, in v2 as in v3; a fill value of a data type nothing in scope reads is not interpreted, so it may hold one. A value that is not JSON no longer stops a declaration's own checks, so the other problems in it are reported; a declaration that holds one is still refused. `typed_json.check` returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. diff --git a/packages/zarr-metadata/changes/493.removal.md b/packages/zarr-metadata/changes/493.removal.md new file mode 100644 index 0000000000..62ec99e562 --- /dev/null +++ b/packages/zarr-metadata/changes/493.removal.md @@ -0,0 +1 @@ +`refine_user_data`, `typed_json.UserJSONValue` and `ExtraFieldDefinition`'s `finite` are removed, since every JSON value may now hold a non-finite number: use `refine_json` and `JSONValue`. diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py index e093160db5..41f9e307a2 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py @@ -165,7 +165,9 @@ def acme_lz4_rules( a TypedDict, `Mapping[str, V]`, a `NewType` and a type alias. A number's type may carry bounds, written with annotated-types and read the way pydantic reads them: `Gt`, `Ge`, `Lt`, `Le` and `Interval`, at most one -from each side, at any depth. For example, +from each side, at any depth. A `float` without bounds may be `NaN`, +`Infinity` or `-Infinity`, so a rule that converts one to an integer +checks it first. For example, `tuple[Annotated[int, Ge(1)], ...]` bounds each element. An integer's type may carry a step, `MultipleOf`, at most one. An array's or a string's type may bound its length with `MinLen`, `MaxLen` and `Len`, so diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py index 4193ae09bf..9bb864522b 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py @@ -481,9 +481,8 @@ def to_key_value( ) -> Mapping[ZarrV3ArrayMetadataStoreKey, bytes]: """The document as a store holds it: JSON bytes at `zarr.json`, spelled by `writer`, a `JSONWriter` or a mapping of its settings. - `NaN`, `Infinity` and `-Infinity` in `attributes` are written as - bare tokens, as zarr-python writes them. A strict JSON parser - rejects these tokens. + `NaN`, `Infinity` and `-Infinity` are written as bare tokens, as + zarr-python writes them. A strict JSON parser rejects these tokens. """ writes = JSONWriter.from_dict(writer) return {ZARR_V3_ARRAY_METADATA_STORE_KEY: writes.encode(self._document)} diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py index 98c5a635c1..aa887af2ae 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py @@ -268,10 +268,8 @@ def to_key_value( ) -> Mapping[ZarrV3GroupMetadataStoreKey, bytes]: """The document as a store holds it: JSON bytes at `zarr.json`, spelled by `writer`, a `JSONWriter` or a mapping of its settings. - `NaN`, `Infinity` and `-Infinity` in `attributes`, or in the - documents the consolidated metadata lists, are written as bare - tokens, as zarr-python writes them. A strict JSON parser rejects - these tokens. + `NaN`, `Infinity` and `-Infinity` are written as bare tokens, as + zarr-python writes them. A strict JSON parser rejects these tokens. """ writes = JSONWriter.from_dict(writer) return {ZARR_V3_GROUP_METADATA_STORE_KEY: writes.encode(self._document)} diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_json_writer.py b/packages/zarr-metadata/src/zarr_metadata/model/_json_writer.py index 59ca10a6e1..920e4ff979 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_json_writer.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_json_writer.py @@ -109,9 +109,8 @@ def encode(self, value: object) -> bytes: The separators are those of Python's `json` module: `", "` between items and `": "` after a key, with the item separator becoming `","` when `indent` is set. A non-finite number is written as a - bare token (`NaN`, `Infinity`, `-Infinity`), as zarr-python writes - attributes; the readers keep such numbers out of every other place - in a document. With `ensure_ascii` off, a lone surrogate (a string + bare token (`NaN`, `Infinity`, `-Infinity`), as Python's `json` + module writes it. With `ensure_ascii` off, a lone surrogate (a string a reader accepts from an escape such as `"\\ud800"`, but which UTF-8 cannot encode) is still written as that escape. """ diff --git a/packages/zarr-metadata/src/zarr_metadata/pydantic.py b/packages/zarr-metadata/src/zarr_metadata/pydantic.py index 308519c0ef..3cd6c3b044 100644 --- a/packages/zarr-metadata/src/zarr_metadata/pydantic.py +++ b/packages/zarr-metadata/src/zarr_metadata/pydantic.py @@ -48,9 +48,11 @@ `InScope`, not with a bare core class, because pydantic cannot build a schema for the core classes. -A node's attributes may hold `NaN`, `Infinity` or `-Infinity`, which the -models read and write as zarr-python does. Pydantic writes JSON by its own -rules, and by default writes such a number as `null`. To keep these +A number in a document may be `NaN`, `Infinity` or `-Infinity` (except +as a float fill value), which the models read and write as zarr-python +does. Pydantic writes JSON by its own rules, and by default writes such a +number as `null`, which changes the document, and which a member typed as +a number refuses when it is read back. To keep these numbers, a `BaseModel` with one of these fields needs `ser_json_inf_nan="constants"` in its `model_config`. A `TypeAdapter` over a field type takes no `config`, so write its value with the model's diff --git a/packages/zarr-metadata/src/zarr_metadata/typed_json.py b/packages/zarr-metadata/src/zarr_metadata/typed_json.py index b666a915e5..613f56821a 100644 --- a/packages/zarr-metadata/src/zarr_metadata/typed_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/typed_json.py @@ -74,7 +74,7 @@ as a JSON Schema. `check` supports only annotations that describe JSON shapes: `int`, -`float` for any number, `bool`, `str`, `None`, `JSONValue`, a `Literal`, +`float` for any number (`NaN`, `Infinity` and `-Infinity` included), `bool`, `str`, `None`, `JSONValue`, a `Literal`, `tuple[T, ...]` and `tuple[T1, T2]`, a union, a TypedDict, `Mapping[str, V]`, a `NewType` and a type alias. A TypedDict that contains anything else raises `TypeError`, naming the member and the From a3aa5e7fd0573d4ff55d3cd3f9d851f568f7b9a6 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 15:07:05 +0100 Subject: [PATCH 22/27] docs(zarr-metadata): say every value spelled as a float fill value is refused as a non-finite number Address NaN review round 2 (no serious findings): - docs/validation-rules.md, the changelog and `non_finite_fill_value`'s docstring named only the fill value and complex components, while the rule also covers a struct's float field and codec scalars spelled as a fill value (`scale_offset`, `cast_value`). The docstring now states the rule once; the other texts follow it. - The definition docs said an unbounded `float` may be non-finite, which implied a bounded one is safe; a one-sided bound admits an infinity. - The removal fragment named the private `refine_user_data` and `refine_json`; it now gives the public removals and their migrations. - Minor wording in the attribute docstrings, the testing strategy, the repair docstring and the `typed_json` module docstring. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/changes/493.feature.md | 2 +- packages/zarr-metadata/changes/493.removal.md | 2 +- .../zarr-metadata/docs/validation-rules.md | 24 +++++++++++-------- .../src/zarr_metadata/definition/__init__.py | 9 +++---- .../zarr_metadata/definition/_definition.py | 12 +++++++++- .../src/zarr_metadata/model/_repair.py | 4 ++-- .../src/zarr_metadata/testing/_document.py | 2 +- .../src/zarr_metadata/typed_json.py | 5 ++-- .../src/zarr_metadata/v3/array.py | 2 +- .../src/zarr_metadata/v3/group.py | 2 +- 10 files changed, 40 insertions(+), 24 deletions(-) diff --git a/packages/zarr-metadata/changes/493.feature.md b/packages/zarr-metadata/changes/493.feature.md index 48569e4631..074872b226 100644 --- a/packages/zarr-metadata/changes/493.feature.md +++ b/packages/zarr-metadata/changes/493.feature.md @@ -1 +1 @@ -Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite (`NaN`, `Infinity`, `-Infinity`, which Python's `json` module reads and writes) is now JSON everywhere: whether a document may hold one is left to the routines that read and write its text. A float's non-finite fill value, or a complex component, must still be written by its name, as each spec says, in v2 as in v3; a fill value of a data type nothing in scope reads is not interpreted, so it may hold one. A value that is not JSON no longer stops a declaration's own checks, so the other problems in it are reported; a declaration that holds one is still refused. `typed_json.check` returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. +Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite (`NaN`, `Infinity`, `-Infinity`, which Python's `json` module reads and writes) is now JSON everywhere: whether a document may hold one is left to the routines that read and write its text. A non-finite value spelled as a float's fill value (the fill value itself, a complex component, a struct field, or a codec scalar such as `scale_offset`'s `scale`) must still be written by its name, as the spec says, in v2 as in v3; a fill value of a data type nothing in scope reads is not interpreted, so it may hold one. A value that is not JSON no longer stops a declaration's own checks, so the other problems in it are reported; a declaration that holds one is still refused. `typed_json.check` returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. diff --git a/packages/zarr-metadata/changes/493.removal.md b/packages/zarr-metadata/changes/493.removal.md index 62ec99e562..42e0e4d47f 100644 --- a/packages/zarr-metadata/changes/493.removal.md +++ b/packages/zarr-metadata/changes/493.removal.md @@ -1 +1 @@ -`refine_user_data`, `typed_json.UserJSONValue` and `ExtraFieldDefinition`'s `finite` are removed, since every JSON value may now hold a non-finite number: use `refine_json` and `JSONValue`. +`typed_json.UserJSONValue` is removed: use `JSONValue`, which may now hold a non-finite number. `ExtraFieldDefinition`'s `finite` argument is removed: drop it, since every extension field may now hold one. diff --git a/packages/zarr-metadata/docs/validation-rules.md b/packages/zarr-metadata/docs/validation-rules.md index 2be74ad7a1..b5dffdbadd 100644 --- a/packages/zarr-metadata/docs/validation-rules.md +++ b/packages/zarr-metadata/docs/validation-rules.md @@ -8,10 +8,10 @@ context. For example: ([`zarr_format`](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#zarr-format) and [`node_type`](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#node-type)), -- a float's non-finite fill value written by its name (`"NaN"`, - `"Infinity"`, `"-Infinity"`); whether JSON text may hold a non-finite - number anywhere else is left to the JSON routines that read and write - it, +- a non-finite value spelled as a float's fill value, written by its + name (`"NaN"`, `"Infinity"`, `"-Infinity"`); whether JSON text may + hold a non-finite number anywhere else is left to the JSON routines + that read and write it, - non-negative [dimensions](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#array-metadata-shape), - one @@ -74,12 +74,16 @@ what the package does. Whether a document may hold them is left to the routines that read and write its text. - The readers, `check` from `zarr_metadata.typed_json`, and the models - accept them wherever a number may stand. `to_key_value` writes them - back as bare tokens, which a strict JSON parser rejects. -- One exception: a float fill value, or a complex fill value component, - that is a non-finite number is refused, because both specs write those - values by name. A fill value of a data type that nothing in the context - reads is not interpreted, so it may hold any number. + accept them wherever a `float` may stand, unless a bound excludes + them. `to_key_value` writes them back as bare tokens, which a strict + JSON parser rejects. +- One exception: a value spelled as a float data type's fill value is + refused when it is a non-finite number, because the spec writes such a + value by its name. That covers the fill value itself, each component + of a complex one, a struct's float field, and a codec's scalars spelled + the same way, such as `scale_offset`'s `scale` and `offset`. A fill + value of a data type that nothing in the context reads is not + interpreted, so it may hold any number. **A reader walks at most 256 levels of nesting.** diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py index 41f9e307a2..9bbb731b9e 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py @@ -165,10 +165,11 @@ def acme_lz4_rules( a TypedDict, `Mapping[str, V]`, a `NewType` and a type alias. A number's type may carry bounds, written with annotated-types and read the way pydantic reads them: `Gt`, `Ge`, `Lt`, `Le` and `Interval`, at most one -from each side, at any depth. A `float` without bounds may be `NaN`, -`Infinity` or `-Infinity`, so a rule that converts one to an integer -checks it first. For example, -`tuple[Annotated[int, Ge(1)], ...]` bounds each element. An integer's +from each side, at any depth. For example, +`tuple[Annotated[int, Ge(1)], ...]` bounds each element. A `float` may +be `NaN`, `Infinity` or `-Infinity` unless its bounds exclude them, and +a bound on one side still admits the infinity on the other, so a rule +that converts a `float` to an integer checks it first. An integer's type may carry a step, `MultipleOf`, at most one. An array's or a string's type may bound its length with `MinLen`, `MaxLen` and `Len`, so `Annotated[tuple[int, ...], MinLen(1)]` is never empty. A value out of diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index 6e8185044c..f200b65f1f 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -145,7 +145,17 @@ def non_finite_name(value: object) -> str | None: def non_finite_fill_value(value: object) -> tuple[ValidationProblem, ...]: - """The problem with `value`, a float fill value or complex fill value component, if it is a number that is not finite. Each spec writes such a value by its name (`non_finite_name`), a string, so the value means the same to a reader whose JSON has no such number. Whether the document's JSON may hold the number at all is for the routines that read its text.""" + """The problem with `value`, a float data type's fill value, if it is a number that is not finite. + + The spec writes such a value by its name (`non_finite_name`), a string, + so the value means the same to a reader whose JSON has no such number. + The rule holds wherever a value is spelled as a float's fill value: the + fill value itself, each component of a complex one, a struct's float + field, and a codec's scalars that are spelled the same way, such as + `scale_offset`'s `scale` and `offset` and `cast_value`'s fill value + and `scalar_map` entries. Whether the document's JSON may hold the + number anywhere else is for the routines that read its text. + """ name = non_finite_name(value) if name is None: return () diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py index c43976d84d..1b6120aeaa 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py @@ -365,8 +365,8 @@ class ZarrV2NonFiniteFillValueArrayMetadataJSON(TypedDict): `"Infinity"` and `"-Infinity"` (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L178-L190), and so does zarr-python since 3.0.7. Python's `json` module reads the - tokens as floats. The fill value is not a member here, since it is a - float, or a pair for a complex dtype, and the repair reads it itself. + tokens as floats. The fill value is not a member here, since its type + depends on the dtype, and the repair reads it itself. """ zarr_format: Literal[2] diff --git a/packages/zarr-metadata/src/zarr_metadata/testing/_document.py b/packages/zarr-metadata/src/zarr_metadata/testing/_document.py index 3e061b20a4..5bef75bf66 100644 --- a/packages/zarr-metadata/src/zarr_metadata/testing/_document.py +++ b/packages/zarr-metadata/src/zarr_metadata/testing/_document.py @@ -78,7 +78,7 @@ ), max_leaves=8, ) -"""JSON values, with JSON arrays as tuples. Only finite numbers, so a drawn value is JSON to every reader.""" +"""JSON values, with JSON arrays as tuples. Only finite numbers, so a drawn value is JSON to a strict JSON parser too.""" _ATTRIBUTES: Final = st.dictionaries(_TEXT, _JSON, max_size=_MAX_MEMBERS) diff --git a/packages/zarr-metadata/src/zarr_metadata/typed_json.py b/packages/zarr-metadata/src/zarr_metadata/typed_json.py index 613f56821a..ccaeab6024 100644 --- a/packages/zarr-metadata/src/zarr_metadata/typed_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/typed_json.py @@ -74,8 +74,9 @@ as a JSON Schema. `check` supports only annotations that describe JSON shapes: `int`, -`float` for any number (`NaN`, `Infinity` and `-Infinity` included), `bool`, `str`, `None`, `JSONValue`, a `Literal`, -`tuple[T, ...]` and `tuple[T1, T2]`, a union, a TypedDict, +`float` for any number (`NaN`, `Infinity` and `-Infinity` included), +`bool`, `str`, `None`, `JSONValue`, a `Literal`, `tuple[T, ...]` and +`tuple[T1, T2]`, a union, a TypedDict, `Mapping[str, V]`, a `NewType` and a type alias. A TypedDict that contains anything else raises `TypeError`, naming the member and the TypedDict that contains it. The same happens for a TypedDict the spec diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/array.py b/packages/zarr-metadata/src/zarr_metadata/v3/array.py index ab0f732162..8de14a7958 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/array.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/array.py @@ -55,7 +55,7 @@ class ZarrV3ArrayMetadataJSON(TypedDict, extra_items=ZarrV3ExtensionField): (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v3/core/index.rst#L974-L983). """ attributes: NotRequired[Mapping[str, JSONValue]] - """User attributes: arbitrary JSON values by string key, whose numbers may also be `NaN`, `Infinity` or `-Infinity`, as zarr-python writes them.""" + """User attributes: arbitrary JSON values by string key, whose numbers may be `NaN`, `Infinity` or `-Infinity`, as zarr-python writes them.""" storage_transformers: NotRequired[tuple[ZarrV3StorageTransformerDeclaration, ...]] """The storage transformers between the array and its store. diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/group.py b/packages/zarr-metadata/src/zarr_metadata/v3/group.py index 235d2df41c..c24dbfc5c2 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/group.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/group.py @@ -26,7 +26,7 @@ class ZarrV3GroupMetadataJSON(TypedDict, extra_items=ZarrV3ExtensionField): node_type: Literal["group"] """The kind of node the document describes, `"group"`.""" attributes: NotRequired[Mapping[str, JSONValue]] - """User attributes: arbitrary JSON values by string key, whose numbers may also be `NaN`, `Infinity` or `-Infinity`, as zarr-python writes them.""" + """User attributes: arbitrary JSON values by string key, whose numbers may be `NaN`, `Infinity` or `-Infinity`, as zarr-python writes them.""" ZarrV3GroupMetadataStoreKey = Literal["zarr.json"] From c27d46c922969112267003038ac6f5aa6c9e3b27 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 16:50:17 +0100 Subject: [PATCH 23/27] refactor(zarr-metadata): let each data type say which fill value numbers it writes by name `non_finite_name` and `non_finite_fill_value` decided, in the layer that knows no data type, how a non-finite number is written. The repair then chose which arrays to apply that to from a list of core type names and a prefix test on the name. Each float type now owns its names: the v3 float types and the v2 float and complex dtypes refuse a non-finite number with their own spec's spelling, and declare it with the new `fill_value_named` hook on `WithFillValue` (complex composes its component's). `named_fill_value` calls the hook for a data type a scope read. The `non_finite_fill_value` repair resolves the array's data type in the scope it is given, a new `context` argument on the repair functions that the repaired readers pass on, and writes what the type names. An extension data type that declares the hook is repaired too; one nothing in the scope reads is left for the strict read. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/changes/493.feature.md | 2 +- packages/zarr-metadata/docs/repair.md | 7 + .../src/zarr_metadata/definition/__init__.py | 11 ++ .../zarr_metadata/definition/_definition.py | 83 +++++---- .../src/zarr_metadata/model/_repair.py | 161 +++++++++++------- .../src/zarr_metadata/v2/data_type/scalar.py | 52 +++++- .../src/zarr_metadata/v3/data_type/_float.py | 69 +++++++- .../zarr_metadata/v3/data_type/complex128.py | 2 + .../zarr_metadata/v3/data_type/complex64.py | 2 + .../src/zarr_metadata/v3/data_type/float16.py | 7 +- .../src/zarr_metadata/v3/data_type/float32.py | 7 +- .../src/zarr_metadata/v3/data_type/float64.py | 7 +- .../zarr-metadata/tests/model/test_repair.py | 37 ++++ .../zarr-metadata/tests/v2/test_data_types.py | 32 ++++ .../tests/v3/test_fill_values.py | 64 +++++++ 15 files changed, 431 insertions(+), 112 deletions(-) diff --git a/packages/zarr-metadata/changes/493.feature.md b/packages/zarr-metadata/changes/493.feature.md index 074872b226..04a52f306d 100644 --- a/packages/zarr-metadata/changes/493.feature.md +++ b/packages/zarr-metadata/changes/493.feature.md @@ -1 +1 @@ -Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides a problem in another. A problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`, and nesting is counted from the root of the input, also in a consolidated listing. A number that is not finite (`NaN`, `Infinity`, `-Infinity`, which Python's `json` module reads and writes) is now JSON everywhere: whether a document may hold one is left to the routines that read and write its text. A non-finite value spelled as a float's fill value (the fill value itself, a complex component, a struct field, or a codec scalar such as `scale_offset`'s `scale`) must still be written by its name, as the spec says, in v2 as in v3; a fill value of a data type nothing in scope reads is not interpreted, so it may hold one. A value that is not JSON no longer stops a declaration's own checks, so the other problems in it are reported; a declaration that holds one is still refused. `typed_json.check` returns each array as a tuple. Some problem messages, and the order problems are reported in, have changed. +Reading a v3 array or group document now checks each member against the document's TypedDict before any declaration is read, so a problem in one member no longer hides another, and a problem in `shape` or `dimension_names` is located at the element, such as `('shape', 1)`. Nesting is counted from the root of the input, also in a consolidated listing. A non-finite number (`NaN`, `Infinity`, `-Infinity`) is now JSON everywhere: whether text may hold one is left to the routines that read and write it. A data type may still refuse a non-finite fill value that it writes by name, as the float types do in both formats, and it declares that spelling with the new `fill_value_named`. `named_fill_value` calls it, and the repair functions use it with a new `context` argument, so an extension data type takes part. A value that is not JSON no longer stops a declaration's own checks. `typed_json.check` returns each array as a tuple. Some problem messages, and their order, have changed. diff --git a/packages/zarr-metadata/docs/repair.md b/packages/zarr-metadata/docs/repair.md index f4f197e40e..b32a1ec258 100644 --- a/packages/zarr-metadata/docs/repair.md +++ b/packages/zarr-metadata/docs/repair.md @@ -39,6 +39,13 @@ Each one works in three steps: [v3 spec](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/data-types/index.html#permitted-fill-values) uses, such as `"NaN"`. +The two fill value repairs ask the array's data type what to write. The +data type is read in the scope the repair is given (`context`, the core +scope by default), and its `fill_value_named` writes each number it +names by that name. So an extension data type that declares +`fill_value_named` is repaired too, and a data type nothing in the scope +reads is left for the strict read. + ## Bugs the repair readers do not undo A document with one of these bugs is refused: diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py index 9bbb731b9e..460ba8b25b 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py @@ -215,6 +215,15 @@ def acme_lz4_rules( gets. `ConstantFillValue(0)` is a default that does not depend on the configuration. `default_fill_value(data_type)` calls it for a data type declaration the scope read. +A type may write some numbers by name: a float writes a `NaN` read from +a document as `"NaN"`, so a number that JSON may hold only as a bare +token means the same to every reader. The rules refuse such a number, +and `fill_value_named` writes each one in a fill value by its name, +returning `UNSET` when there is none, which is what a data type that +does not declare it gets. `named_fill_value(data_type, value)` calls it +for a data type declaration the scope read; the +`non_finite_fill_value` repair uses it, so a data type in the repair's +scope decides what the repair writes. **The simplest spelling.** A declaration without problems has a simplest equivalent spelling, and declarations are compared by it. Each nested declaration is @@ -298,6 +307,7 @@ def acme_lz4_rules( configuration_of, default_fill_value, fill_value_problems, + named_fill_value, resolve, with_problems, ) @@ -326,6 +336,7 @@ def acme_lz4_rules( "configuration_of", "default_fill_value", "fill_value_problems", + "named_fill_value", "resolve", "with_problems", ] diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index f200b65f1f..3540a8e419 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -40,7 +40,6 @@ import dataclasses import functools -import math from collections.abc import Callable, Iterable, Iterator, Mapping from dataclasses import dataclass from types import MappingProxyType @@ -135,37 +134,9 @@ def no_fill_value_default(*_: object) -> UNSET: return UNSET -def non_finite_name(value: object) -> str | None: - """The name both formats' specs give `value`, a number that is not finite, as a float fill value: `"NaN"`, `"Infinity"` or `"-Infinity"`. None for any other value.""" - if not isinstance(value, float) or math.isfinite(value): - return None - if math.isnan(value): - return "NaN" - return "Infinity" if value > 0 else "-Infinity" - - -def non_finite_fill_value(value: object) -> tuple[ValidationProblem, ...]: - """The problem with `value`, a float data type's fill value, if it is a number that is not finite. - - The spec writes such a value by its name (`non_finite_name`), a string, - so the value means the same to a reader whose JSON has no such number. - The rule holds wherever a value is spelled as a float's fill value: the - fill value itself, each component of a complex one, a struct's float - field, and a codec's scalars that are spelled the same way, such as - `scale_offset`'s `scale` and `offset` and `cast_value`'s fill value - and `scalar_map` entries. Whether the document's JSON may hold the - number anywhere else is for the routines that read its text. - """ - name = non_finite_name(value) - if name is None: - return () - return ( - ValidationProblem( - (), - f"expected a non-finite value written by its name, {name!r}, got the number {name}", - "invalid_value", - ), - ) +def no_fill_value_named(*_: object) -> UNSET: + """The named spelling of a fill value for a data type that writes no number by name: `UNSET`, as there is nothing to write.""" + return UNSET @dataclass(frozen=True, slots=True, eq=False) @@ -528,6 +499,10 @@ class WithFillValue(Definition[C]): fill value of an array whose document is built without one, as the models' `create_default` builds it. It receives the configuration and the nested declarations, and returns `UNSET` when the type has none. + `fill_value_named` writes each number in a fill value of that shape + that the type writes by name, such as a float's `NaN` as `"NaN"`, by + that name. It receives the same arguments as the rules, and returns + `UNSET` when the fill value holds no such number. """ fill_value: object = JSONValue @@ -538,6 +513,8 @@ class WithFillValue(Definition[C]): """A fill value without problems, in the single canonical spelling of its value.""" fill_value_default: Callable[[C, Nested], JSONValue | UNSET] = no_fill_value_default """The fill value of an array built without one, such as `0` for `int8`; `UNSET` when the type has none.""" + fill_value_named: Callable[[C, Nested, Any], JSONValue | UNSET] = no_fill_value_named + """A fill value of that shape with each number the type writes by name written by that name; `UNSET` when it holds none.""" def _refusal(self) -> str | None: try: @@ -1696,6 +1673,44 @@ def spelled_canonically(data_type: ResolvedDeclaration[F], value: JSONValue) -> return refined +def named_fill_value(data_type: ResolvedDeclaration[F], value: object) -> JSONValue | UNSET: + """`value` (a fill value of `data_type`, a data type declaration a scope read) with each number the data type writes by name written by that name, such as a float's `NaN` as `"NaN"`. + + The names come from the data type's `fill_value_named`. The result is + `UNSET` when `value` holds no such number, when it is not JSON or not + of the data type's fill value shape, and when the scope did not read + the data type. The data type's function is the extension author's + code: its result is checked to be JSON, and an error it raises gets a + note that says which data type raised it. + """ + if not isinstance(data_type, AcceptedDeclaration): + return UNSET + refined, problems = refine_json(value, ()) + if len(problems) != 0: + return UNSET + definition, configuration = data_type.definition, data_type.configuration + typed, problems = _fill_value_parser(definition.fill_value)(refined, ()) + if not _usable(problems): + return UNSET + named = asked( + definition, + "fill_value_named", + lambda: cast( + "object", definition.fill_value_named(read_only(configuration), data_type.nested, typed) + ), + ) + if named is UNSET: + return UNSET + written, problems = refine_json(named, ()) + if len(problems) != 0: + msg = ( + f"{definition.name!r}: its fill_value_named gives JSON or UNSET, got {named!r}: " + f"{problems[0].message}" + ) + raise TypeError(msg) + return written + + def resolve( data: object, kind: type[D], context: Context, loc: Loc = () ) -> tuple[ResolvedDeclaration[D], Problems]: @@ -2209,9 +2224,9 @@ def _replaced(value: JSONValue, path: Loc, new: JSONValue) -> JSONValue: "item_at", "kind_of", "named_configuration", + "named_fill_value", + "no_fill_value_named", "no_rules", - "non_finite_fill_value", - "non_finite_name", "own_key", "read_found", "read_only", diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py index 1b6120aeaa..8751a909b5 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py @@ -19,7 +19,7 @@ from collections.abc import Mapping from dataclasses import dataclass -from typing import TYPE_CHECKING, Annotated, Literal, TypeAlias, TypedDict, cast +from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeAlias, TypedDict, cast from annotated_types import Ge @@ -32,11 +32,16 @@ is_list_or_tuple, is_object, ) +from zarr_metadata._sentinel import UNSET from zarr_metadata._typed_json import Loc, check from zarr_metadata.definition._context import ( scoped, ) -from zarr_metadata.definition._definition import non_finite_name +from zarr_metadata.definition._definition import ( + ResolvedDeclaration, + named_fill_value, + resolve, +) from zarr_metadata.model._group_v2 import ( ZarrV2ConsolidatedMetadataReading, ZarrV2NodeMetadataReading, @@ -44,10 +49,12 @@ read_node_metadata_v2, ) from zarr_metadata.model._group_v3 import ZarrV3NodeMetadataReading, read_node_metadata_v3 +from zarr_metadata.v2._definition import ZarrV2DataTypeDefinition from zarr_metadata.v2.array import ZARR_V2_ARRAY_METADATA_STORE_KEY from zarr_metadata.v2.definition import CORE_V2_CONTEXT from zarr_metadata.v2.group import ZARR_V2_GROUP_METADATA_STORE_KEY from zarr_metadata.v3._core import CORE_AND_EXTENSIONS_CONTEXT +from zarr_metadata.v3._definition import DataTypeDefinition from zarr_metadata.v3.consolidated import ZARR_V3_CONSOLIDATED_METADATA_KEY if TYPE_CHECKING: @@ -125,16 +132,19 @@ class ZarrV3NonFiniteFillValueArrayMetadataJSON(TypedDict): zarr-python 3.0.0 to 3.0.6 wrote the fill value of a float64 array, in the documents a group's consolidated metadata lists, as a bare `NaN`, `Infinity` or `-Infinity`. The spec writes these as - the strings `"NaN"`, `"Infinity"` and `"-Infinity"`. The repair writes - each such fill value, or complex fill value component, of a float or - complex data type by its name. + the strings `"NaN"`, `"Infinity"` and `"-Infinity"`. The repair asks + the data type, read in the context, to write each number it names by + that name (`named_fill_value`), so a float's fill value and each + component of a complex one are written by name. """ node_type: Literal["array"] - data_type: Literal["float16", "float32", "float64", "complex64", "complex128"] + data_type: JSONValue -def repair_node_metadata_v3(value: object) -> tuple[object, tuple[Repair, ...]]: +def repair_node_metadata_v3( + value: object, *, context: ZarrV3Context | None = None +) -> tuple[object, tuple[Repair, ...]]: """Undo each known writer bug in `value`, a v3 `zarr.json`, and return the result with the list of changes. Each document in the consolidated metadata is repaired too. A group @@ -142,12 +152,14 @@ def repair_node_metadata_v3(value: object) -> tuple[object, tuple[Repair, ...]]: them from the repaired group's member. Content that no repair applies to is left as it is. `value` is not modified: a repaired document is a new object, which shares its unchanged parts with `value`. A document - with none of the bugs is returned as it is, with no repairs. + with none of the bugs is returned as it is, with no repairs. A repair + that depends on a data type reads it in `context` + (`CORE_AND_EXTENSIONS_CONTEXT` by default). """ - return _repaired(value, ()) + return _repaired(value, (), scoped(context, CORE_AND_EXTENSIONS_CONTEXT)) -def _repaired(value: object, at: Loc) -> tuple[object, tuple[Repair, ...]]: +def _repaired(value: object, at: Loc, context: ZarrV3Context) -> tuple[object, tuple[Repair, ...]]: if not is_json_object(value) or len(at) >= JSON_DEPTH: # Not a document, or nested deeper than a reader walks. The strict # read reports both. @@ -158,22 +170,23 @@ def _repaired(value: object, at: Loc) -> tuple[object, tuple[Repair, ...]]: if len(at) != 0: # The writer bug is in the documents a listing holds only. Those # versions wrote a node's own `zarr.json` correctly. - document = _non_finite_fill_value_v3(document, at, repairs) + document = _non_finite_fill_value_v3(document, at, repairs, context) document = _null_consolidated_metadata(document, at, repairs) - document = _consolidated(document, at, repairs) + document = _consolidated(document, at, repairs, context) return (original if len(repairs) == 0 else dict(document)), tuple(repairs) def _non_finite_fill_value_v3( - document: Mapping[str, object], at: Loc, repairs: list[Repair] + document: Mapping[str, object], at: Loc, repairs: list[Repair], context: ZarrV3Context ) -> Mapping[str, object]: - """`document` with a non-finite fill value of a float data type, or complex fill value component, written by its name.""" + """`document` with each number in its fill value that its data type writes by name written by that name.""" array, problems = check( _members(document, ("node_type", "data_type")), ZarrV3NonFiniteFillValueArrayMetadataJSON ) if array is None or len(problems) != 0 or "fill_value" not in document: return document - return _non_finite_named(document, array["data_type"].startswith("float"), at, repairs) + data_type, _ = resolve(array["data_type"], DataTypeDefinition, context) + return _named(document, data_type, at, repairs) def _members(document: Mapping[str, object], keys: tuple[str, ...]) -> dict[str, object]: @@ -234,7 +247,7 @@ def _null_consolidated_metadata( def _consolidated( - document: Mapping[str, object], at: Loc, repairs: list[Repair] + document: Mapping[str, object], at: Loc, repairs: list[Repair], context: ZarrV3Context ) -> Mapping[str, object]: """`document` with each document in its consolidated metadata repaired, if it has any.""" member = document.get(ZARR_V3_CONSOLIDATED_METADATA_KEY) @@ -249,7 +262,7 @@ def _consolidated( for key, entry in entries.items(): if isinstance(key, str): entry, inside = _repaired( - entry, (*at, ZARR_V3_CONSOLIDATED_METADATA_KEY, "metadata", key) + entry, (*at, ZARR_V3_CONSOLIDATED_METADATA_KEY, "metadata", key), context ) repairs.extend(inside) held[key] = entry @@ -279,7 +292,7 @@ def read_repaired_node_metadata_v3( same way `read_node_metadata_v3` reports it. """ context = scoped(context, CORE_AND_EXTENSIONS_CONTEXT) - repaired, repairs = repair_node_metadata_v3(value) + repaired, repairs = repair_node_metadata_v3(value, context=context) return ZarrV3RepairedNodeMetadataReading( read_node_metadata_v3(repaired, context=context), repairs ) @@ -292,17 +305,21 @@ class ZarrV2ZGroupWithConsolidatedMetadataJSON(TypedDict): consolidated_metadata: Mapping[str, JSONValue] -def repair_consolidated_metadata_v2(value: object) -> tuple[object, tuple[Repair, ...]]: +def repair_consolidated_metadata_v2( + value: object, *, context: ZarrV2Context | None = None +) -> tuple[object, tuple[Repair, ...]]: """Undo each known writer bug in `value`, a v2 `.zmetadata`, and return the result with the list of changes. zarr-python 3.x writes a `consolidated_metadata` member into each `.zgroup` entry below the root. This function removes it. The root's entry is left alone, since no writer puts the member there. Each `.zarray` entry is repaired as `repair_node_metadata_v2` repairs a - `.zarray`. Content that no repair applies to is left as it is, and + `.zarray`, with each dtype read in `context` (`CORE_V2_CONTEXT` by + default). Content that no repair applies to is left as it is, and `value` is not modified. A document with none of the bugs is returned as it is, with no repairs. """ + context = scoped(context, CORE_V2_CONTEXT) if not is_json_object(value): return value, () document = value @@ -318,7 +335,7 @@ def repair_consolidated_metadata_v2(value: object) -> tuple[object, tuple[Repair if name == ZARR_V2_GROUP_METADATA_STORE_KEY and path.strip("/") != "": entry = _without_consolidated_metadata(entry, ("metadata", key), repairs) if name == ZARR_V2_ARRAY_METADATA_STORE_KEY: - entry = _repaired_zarray(entry, ("metadata", key), repairs) + entry = _repaired_zarray(entry, ("metadata", key), repairs, context) held[key] = entry if len(repairs) == 0: return value, () @@ -350,13 +367,8 @@ def _without_consolidated_metadata(entry: object, at: Loc, repairs: list[Repair] return kept -_ZarrV2FloatTypestr: TypeAlias = Literal[ - "f2", "f4", "f8", "c8", "c16" -] - - class ZarrV2NonFiniteFillValueArrayMetadataJSON(TypedDict): - """The members of a `.zarray` that the `non_finite_fill_value` repair reads, other than the fill value: a float or complex `dtype`. + """The members of a `.zarray` that the `non_finite_fill_value` repair reads, other than the fill value: the `dtype`, which the repair reads in its scope. zarr-python 3.0.0 to 3.0.6 wrote a non-finite fill value of a float array as a bare token, `"fill_value": NaN`, and each non-finite @@ -365,84 +377,103 @@ class ZarrV2NonFiniteFillValueArrayMetadataJSON(TypedDict): `"Infinity"` and `"-Infinity"` (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L178-L190), and so does zarr-python since 3.0.7. Python's `json` module reads the - tokens as floats. The fill value is not a member here, since its type - depends on the dtype, and the repair reads it itself. + tokens as floats. The repair asks the dtype to write each number it + names by that name (`named_fill_value`). The fill value is not a + member here, since its type depends on the dtype, and the repair reads + it itself. """ zarr_format: Literal[2] - dtype: _ZarrV2FloatTypestr + dtype: JSONValue def repair_node_metadata_v2( - files: Mapping[str, object], + files: Mapping[str, object], *, context: ZarrV2Context | None = None ) -> tuple[Mapping[str, object], tuple[Repair, ...]]: """Undo each known writer bug in `files`, a v2 node's files as `read_node_metadata_v2` takes them, and return the result with the list of changes. zarr-python 3.0.0 to 3.0.6 wrote a non-finite fill value in a `.zarray` as a bare token, `NaN`, which Python's `json` module reads as - a float. This function writes it as the string the v2 spec uses, - `"NaN"`, and does the same for each component of a complex fill value. - Each repair is located in `files`, under the name of the file. Content - that no repair applies to is left as it is, and `files` is not - modified. Files with none of the bugs are returned as they are, with - no repairs. + a float. This function asks the dtype, read in `context` + (`CORE_V2_CONTEXT` by default), to write each number it names by that + name: a float's `NaN` as `"NaN"`, the string the v2 spec uses, and each + component of a complex fill value the same way. Each repair is located + in `files`, under the name of the file. Content that no repair applies + to is left as it is, and `files` is not modified. Files with none of + the bugs are returned as they are, with no repairs. """ + context = scoped(context, CORE_V2_CONTEXT) if ZARR_V2_ARRAY_METADATA_STORE_KEY not in files: return files, () repairs: list[Repair] = [] zarray = _repaired_zarray( - files[ZARR_V2_ARRAY_METADATA_STORE_KEY], (ZARR_V2_ARRAY_METADATA_STORE_KEY,), repairs + files[ZARR_V2_ARRAY_METADATA_STORE_KEY], + (ZARR_V2_ARRAY_METADATA_STORE_KEY,), + repairs, + context, ) if len(repairs) == 0: return files, () return {**files, ZARR_V2_ARRAY_METADATA_STORE_KEY: zarray}, tuple(repairs) -def _repaired_zarray(entry: object, at: Loc, repairs: list[Repair]) -> object: +def _repaired_zarray( + entry: object, at: Loc, repairs: list[Repair], context: ZarrV2Context +) -> object: """`entry`, a `.zarray` document, with each known writer bug in it undone.""" if not is_json_object(entry): return entry - return _non_finite_fill_value(entry, at, repairs) + return _non_finite_fill_value(entry, at, repairs, context) def _non_finite_fill_value( - document: Mapping[str, object], at: Loc, repairs: list[Repair] + document: Mapping[str, object], at: Loc, repairs: list[Repair], context: ZarrV2Context ) -> Mapping[str, object]: - """`document` with a non-finite float fill value, or complex fill value component, written by its name.""" + """`document` with each number in its fill value that its dtype writes by name written by that name.""" array, problems = check( _members(document, ("zarr_format", "dtype")), ZarrV2NonFiniteFillValueArrayMetadataJSON ) if array is None or len(problems) != 0 or "fill_value" not in document: return document - return _non_finite_named(document, array["dtype"][1] == "f", at, repairs) + data_type, _ = resolve(array["dtype"], ZarrV2DataTypeDefinition, context) + return _named(document, data_type, at, repairs) -def _non_finite_named( - document: Mapping[str, object], is_float: bool, at: Loc, repairs: list[Repair] +def _named( + document: Mapping[str, object], + data_type: ResolvedDeclaration[Any], + at: Loc, + repairs: list[Repair], ) -> Mapping[str, object]: - """`document`, an array of either format with a `fill_value` of a float data type when `is_float` and of a complex one otherwise, with a non-finite fill value, or complex fill value component, written by its name. Each name written is added to `repairs`, located under `at`.""" + """`document`, an array of either format whose data type is `data_type`, with each number in its fill value that the data type writes by name written by that name. Each name written is added to `repairs`, located under `at`.""" fill_value = document["fill_value"] - if is_float: - name = non_finite_name(fill_value) - if name is None: - return document - repairs.append(_non_finite_repair((*at, "fill_value"), name, "a fill value")) - return {**document, "fill_value": name} - if not is_list_or_tuple(fill_value) or len(fill_value) != 2: + named = named_fill_value(data_type, fill_value) + if named is UNSET: return document - names = [non_finite_name(component) for component in fill_value] - if all(name is None for name in names): + loc = (*at, "fill_value") + written = _names_written(fill_value, named, loc) + if len(written) == 0: return document repairs.extend( - _non_finite_repair((*at, "fill_value", index), name, "a fill value component") - for index, name in enumerate(names) - if name is not None - ) - repaired = tuple( - component if name is None else name - for component, name in zip(fill_value, names, strict=True) + _non_finite_repair( + where, name, "a fill value" if where == loc else "a fill value component" + ) + for where, name in written ) - return {**document, "fill_value": repaired} + return {**document, "fill_value": named} + + +def _names_written(before: object, after: object, loc: Loc) -> list[tuple[Loc, str]]: + """Each place under `loc` where `after` writes by name, as a string, what `before` holds as a number, with that name.""" + if isinstance(after, str): + return [] if isinstance(before, str) else [(loc, after)] + if not (is_list_or_tuple(before) and is_list_or_tuple(after)) or len(before) != len(after): + return [] + return [ + found + for index, (old, new) in enumerate(zip(before, after, strict=True)) + for found in _names_written(old, new, (*loc, index)) + ] def _non_finite_repair(loc: Loc, name: str, what: str) -> Repair: @@ -474,7 +505,7 @@ def read_repaired_node_metadata_v2( same way `read_node_metadata_v2` reports it. """ context = scoped(context, CORE_V2_CONTEXT) - repaired, repairs = repair_node_metadata_v2(files) + repaired, repairs = repair_node_metadata_v2(files, context=context) return ZarrV2RepairedNodeMetadataReading( read_node_metadata_v2(repaired, context=context), repairs ) @@ -502,7 +533,7 @@ def read_repaired_consolidated_metadata_v2( `read_consolidated_metadata_v2` reports it. """ context = scoped(context, CORE_V2_CONTEXT) - repaired, repairs = repair_consolidated_metadata_v2(value) + repaired, repairs = repair_consolidated_metadata_v2(value, context=context) return ZarrV2RepairedConsolidatedMetadataReading( read_consolidated_metadata_v2(repaired, context=context), repairs ) diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py index 6133c16e61..67f0df91db 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py @@ -9,7 +9,8 @@ from typing import TYPE_CHECKING, Final from zarr_metadata._json import ValidationProblem -from zarr_metadata.definition._definition import ConstantFillValue, non_finite_fill_value +from zarr_metadata._sentinel import UNSET +from zarr_metadata.definition._definition import ConstantFillValue from zarr_metadata.v2._definition import ZarrV2DataTypeDefinition from zarr_metadata.v2._types.data_type import ( ZarrV2ByteOrder, @@ -55,21 +56,60 @@ def __call__( def _float_fill_value_rules( configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2FloatFillValue ) -> Iterator[ValidationProblem]: - """The rule for a float fill value: a number that is not finite is written by its name.""" - yield from non_finite_fill_value(value) + """The rule for a float fill value: a number that is not finite is written by its name, as the v2 spec spells it.""" + name = _named(value) + if name is not None: + yield ValidationProblem( + (), + f"expected a non-finite value written by its name, {name!r}, got the number {name}", + "invalid_value", + ) def _complex_fill_value_rules( configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2ComplexFillValue ) -> Iterator[ValidationProblem]: - """The rule for a complex fill value: a component that is a number that is not finite is written by its name, as a float fill value is.""" + """The rule for a complex fill value: each component is checked at its index as a float fill value is.""" if value is None: return for index, part in enumerate(value): - for found in non_finite_fill_value(part): + for found in _float_fill_value_rules(configuration, nested, part): yield dataclasses.replace(found, loc=(index, *found.loc)) +def _float_named( + configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2FloatFillValue +) -> ZarrV2FloatSpecial | UNSET: + """Return `value`, a float fill value, written by the name the v2 spec gives it when it is a number that is not finite. `UNSET` for any other value.""" + name = _named(value) + return UNSET if name is None else name + + +def _complex_named( + configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2ComplexFillValue +) -> ZarrV2ComplexFillValue | UNSET: + """Return `value`, a complex fill value, with each component that is a number that is not finite written by its name. `UNSET` when it has no such component.""" + if value is None: + return UNSET + real, imag = value + real_name, imag_name = _named(real), _named(imag) + if real_name is None and imag_name is None: + return UNSET + return (real if real_name is None else real_name, imag if imag_name is None else imag_name) + + +def _named(value: ZarrV2FloatFillValue) -> ZarrV2FloatSpecial | None: + """The name the v2 spec gives `value` when it is a number that is not finite: `"NaN"`, `"Infinity"` or `"-Infinity"` + (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L178-L190). + None for any other value. An integer is finite, and may be too large to convert to a float. + """ + if not isinstance(value, float) or math.isfinite(value): + return None + if math.isnan(value): + return "NaN" + return "Infinity" if value > 0 else "-Infinity" + + def _float_canonical( configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2FloatFillValue ) -> ZarrV2FloatFillValue: @@ -154,6 +194,7 @@ def _complex_canonical( fill_value_rules=_float_fill_value_rules, fill_value_default=ConstantFillValue(0.0), fill_value_canonical=_float_canonical, + fill_value_named=_float_named, ) """`f2`, `f4`, `f8`: IEEE 754 floats. The fill value is a number or a named non-finite value.""" @@ -165,6 +206,7 @@ def _complex_canonical( fill_value_rules=_complex_fill_value_rules, fill_value_default=ConstantFillValue((0.0, 0.0)), fill_value_canonical=_complex_canonical, + fill_value_named=_complex_named, ) """`c8`, `c16`: complex floats. The fill value is `[real, imag]`.""" 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 8d7c784c4b..449bf3fa9d 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 @@ -12,6 +12,7 @@ """ import dataclasses +import math import struct from collections.abc import Callable, Iterable, Iterator from dataclasses import dataclass @@ -20,8 +21,9 @@ from zarr_metadata._common import EmptyConfiguration, JSONValue from zarr_metadata._json import ValidationProblem, choices, shown -from zarr_metadata.definition._definition import Nested, non_finite_fill_value -from zarr_metadata.v3._types.data_type import FLOAT_SPECIAL_FILL_VALUES +from zarr_metadata._sentinel import UNSET +from zarr_metadata.definition._definition import Nested +from zarr_metadata.v3._types.data_type import FLOAT_SPECIAL_FILL_VALUES, FloatSpecialFillValue def float_fill_value_rules( @@ -30,7 +32,9 @@ def float_fill_value_rules( """Return the fill value rules of the floating-point type `name`. `hex_form` accepts its hex strings. A finite number may have any value, because a reader rounds it. A - number that is not finite is written by its name. A string + number that is not finite (`NaN`, `Infinity` or `-Infinity`, as + Python's `json` module reads them) is a problem, because the spec + writes such a value by its name, `float_fill_value_named`. A string must be one of the named values, or a hex string of the type's own width. The type-checked shape accepts any string here, so `hex_form` raises `ValueError` for a string that is not a valid hex string. @@ -49,7 +53,14 @@ def __call__( self, configuration: EmptyConfiguration, nested: Nested, value: float | str ) -> Iterator[ValidationProblem]: if not isinstance(value, str): - yield from non_finite_fill_value(value) + name = _named(value) + if name is not None: + yield ValidationProblem( + (), + f"expected a non-finite value written by its name, {name!r}, " + f"got the number {name}", + "invalid_value", + ) return if value in FLOAT_SPECIAL_FILL_VALUES: return @@ -64,6 +75,24 @@ def __call__( ) +def float_fill_value_named( + configuration: EmptyConfiguration, nested: Nested, value: float | str +) -> FloatSpecialFillValue | UNSET: + """Return `value`, a float fill value, written by the name the spec gives it, when it is a number that is not finite: `"NaN"`, `"Infinity"` or `"-Infinity"`. `UNSET` for any other value.""" + name = None if isinstance(value, str) else _named(value) + return UNSET if name is None else name + + +def _named(value: float) -> FloatSpecialFillValue | None: + """The name the spec gives `value`, a number, when it is not finite. None for a finite number.""" + if not isinstance(value, float) or math.isfinite(value): + # An integer is finite, and may be too large to convert to a float. + return None + if math.isnan(value): + return "NaN" + return "Infinity" if value > 0 else "-Infinity" + + FloatWidth = Literal[16, 32, 64] """The widths, in bits, of the IEEE 754 binary formats the float types store.""" @@ -239,11 +268,43 @@ def __call__( return tuple(self.component(configuration, nested, part) for part in value) +def complex_fill_value_named( + component: Callable[[EmptyConfiguration, Nested, float | str], JSONValue | UNSET], +) -> Callable[[EmptyConfiguration, Nested, tuple[float | str, float | str]], JSONValue | UNSET]: + """Return the named spelling of a complex fill value. Each component is named by `component`, the named spelling of its float type, and a component it does not name is kept.""" + return _ComplexNamed(component) + + +@dataclass(frozen=True, slots=True) +class _ComplexNamed: + """The named spelling of a complex fill value. This is a value rather than a closure, for the same reason as `_FloatFillValue`.""" + + component: Callable[[EmptyConfiguration, Nested, float | str], JSONValue | UNSET] + + def __call__( + self, + configuration: EmptyConfiguration, + nested: Nested, + value: tuple[float | str, float | str], + ) -> JSONValue | UNSET: + real, imag = value + real_name = self.component(configuration, nested, real) + imag_name = self.component(configuration, nested, imag) + if real_name is UNSET and imag_name is UNSET: + return UNSET + return ( + real if real_name is UNSET else real_name, + imag if imag_name is UNSET else imag_name, + ) + + __all__ = [ "FloatWidth", "complex_fill_value_canonical", + "complex_fill_value_named", "complex_fill_value_rules", "float_bits", "float_fill_value_canonical", + "float_fill_value_named", "float_fill_value_rules", ] 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 43a70bd7d4..c7780f664d 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 @@ -20,6 +20,7 @@ ) from zarr_metadata.v3.data_type._float import ( complex_fill_value_canonical, + complex_fill_value_named, complex_fill_value_rules, ) from zarr_metadata.v3.data_type.float64 import FLOAT64_DATA_TYPE @@ -31,6 +32,7 @@ fill_value_default=ConstantFillValue((0.0, 0.0)), 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), + fill_value_named=complex_fill_value_named(FLOAT64_DATA_TYPE.fill_value_named), storage=multi_byte, number_class="complex", ) 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 e8ba97aab0..87819b335a 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 @@ -20,6 +20,7 @@ ) from zarr_metadata.v3.data_type._float import ( complex_fill_value_canonical, + complex_fill_value_named, complex_fill_value_rules, ) from zarr_metadata.v3.data_type.float32 import FLOAT32_DATA_TYPE @@ -31,6 +32,7 @@ fill_value_default=ConstantFillValue((0.0, 0.0)), 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), + fill_value_named=complex_fill_value_named(FLOAT32_DATA_TYPE.fill_value_named), storage=multi_byte, number_class="complex", ) 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 27725e8925..ec7bc5c37e 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 @@ -23,7 +23,11 @@ Float16SpecialFillValue, HexFloat16, ) -from zarr_metadata.v3.data_type._float import float_fill_value_canonical, float_fill_value_rules +from zarr_metadata.v3.data_type._float import ( + float_fill_value_canonical, + float_fill_value_named, + float_fill_value_rules, +) _HEX_FLOAT16_RE: Final = re.compile(r"^0x[0-9a-fA-F]{4}$") @@ -46,6 +50,7 @@ def hex_float16(value: str) -> HexFloat16: fill_value_default=ConstantFillValue(0.0), fill_value_rules=float_fill_value_rules("float16", hex_float16), fill_value_canonical=float_fill_value_canonical(16), + fill_value_named=float_fill_value_named, storage=multi_byte, number_class="floating_point", ) 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 d265b3d69f..792155ed83 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 @@ -23,7 +23,11 @@ Float32SpecialFillValue, HexFloat32, ) -from zarr_metadata.v3.data_type._float import float_fill_value_canonical, float_fill_value_rules +from zarr_metadata.v3.data_type._float import ( + float_fill_value_canonical, + float_fill_value_named, + float_fill_value_rules, +) _HEX_FLOAT32_RE: Final = re.compile(r"^0x[0-9a-fA-F]{8}$") @@ -46,6 +50,7 @@ def hex_float32(value: str) -> HexFloat32: fill_value_default=ConstantFillValue(0.0), fill_value_rules=float_fill_value_rules("float32", hex_float32), fill_value_canonical=float_fill_value_canonical(32), + fill_value_named=float_fill_value_named, storage=multi_byte, number_class="floating_point", ) 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 db50d6a14f..e862967560 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 @@ -23,7 +23,11 @@ Float64SpecialFillValue, HexFloat64, ) -from zarr_metadata.v3.data_type._float import float_fill_value_canonical, float_fill_value_rules +from zarr_metadata.v3.data_type._float import ( + float_fill_value_canonical, + float_fill_value_named, + float_fill_value_rules, +) _HEX_FLOAT64_RE: Final = re.compile(r"^0x[0-9a-fA-F]{16}$") @@ -46,6 +50,7 @@ def hex_float64(value: str) -> HexFloat64: fill_value_default=ConstantFillValue(0.0), fill_value_rules=float_fill_value_rules("float64", hex_float64), fill_value_canonical=float_fill_value_canonical(64), + fill_value_named=float_fill_value_named, storage=multi_byte, number_class="floating_point", ) diff --git a/packages/zarr-metadata/tests/model/test_repair.py b/packages/zarr-metadata/tests/model/test_repair.py index ebaf90200a..01c2f09076 100644 --- a/packages/zarr-metadata/tests/model/test_repair.py +++ b/packages/zarr-metadata/tests/model/test_repair.py @@ -9,6 +9,7 @@ import pytest +from zarr_metadata.definition import EmptyConfiguration from zarr_metadata.model import ( ZarrV2ArrayMetadata, ZarrV2ConsolidatedMetadata, @@ -26,6 +27,13 @@ repair_node_metadata_v3, ) from zarr_metadata.problems import MetadataValidationError +from zarr_metadata.v2.definition import ZarrV2Context +from zarr_metadata.v3.data_type._float import float_fill_value_named +from zarr_metadata.v3.definition import ( + CORE_AND_EXTENSIONS_CONTEXT, + DataTypeDefinition, + ZarrV3Context, +) ARRAY: dict[str, Any] = dict(ZarrV3ArrayMetadata.create_default(shape=(0, 3)).to_json()) GROUP: dict[str, Any] = {"zarr_format": 3, "node_type": "group"} @@ -303,6 +311,35 @@ def test_repair_v2_node_writes_a_bare_non_finite_fill_value_by_name( assert document is files +ACME_HALF = DataTypeDefinition( + name="acme.half", + configuration=EmptyConfiguration, + fill_value=float | str, + fill_value_named=float_fill_value_named, +) +"""An extension data type that writes a non-finite fill value by name, as the float types do.""" + + +def test_repair_writes_by_name_what_the_data_type_in_its_scope_names() -> None: + """The `non_finite_fill_value` repair asks the data type, read in the repair's scope, what to write by name, so an extension data type takes part and a type nothing in scope reads is left alone.""" + acme = CORE_AND_EXTENSIONS_CONTEXT.union(ZarrV3Context(data_types=[ACME_HALF])) + value = _consolidated(a={**ARRAY, "data_type": "acme.half", "fill_value": math.nan}) + document, made = repair_node_metadata_v3(value, context=acme) + assert json.dumps(document) == json.dumps( + _consolidated(a={**ARRAY, "data_type": "acme.half", "fill_value": "NaN"}) + ) + at = ("consolidated_metadata", "metadata", "a", "fill_value") + assert [(repair.loc, repair.kind) for repair in made] == [(at, "non_finite_fill_value")] + assert read_repaired_node_metadata_v3(value, context=acme).repairs == made + assert repair_node_metadata_v3(value) == (value, ()) + # A v2 scope that reads no float dtype leaves a bare NaN for the strict read. + no_floats = ZarrV2Context(data_types=[]) + assert repair_node_metadata_v2({".zarray": NAN_ZARRAY}, context=no_floats)[1] == () + zmetadata = {"zarr_consolidated_format": 1, "metadata": {"a/.zarray": NAN_ZARRAY}} + assert repair_consolidated_metadata_v2(zmetadata, context=no_floats)[1] == () + assert read_repaired_node_metadata_v2({".zarray": NAN_ZARRAY}, context=no_floats).repairs == () + + @pytest.mark.parametrize( ("files", "model", "repaired_at"), [ diff --git a/packages/zarr-metadata/tests/v2/test_data_types.py b/packages/zarr-metadata/tests/v2/test_data_types.py index c1d7f600d4..5f018673c2 100644 --- a/packages/zarr-metadata/tests/v2/test_data_types.py +++ b/packages/zarr-metadata/tests/v2/test_data_types.py @@ -17,6 +17,7 @@ canonical_of, default_fill_value, fill_value_problems, + named_fill_value, resolve, ) from zarr_metadata.definition._definition import declarations_of @@ -320,6 +321,37 @@ def test_a_struct_record_type_sits_where_the_document_writes_it() -> None: ] +@pytest.mark.parametrize( + ("dtype", "value", "named"), + [ + ("f4", math.inf, "Infinity"), + (" None: + resolved, found = resolve(dtype, ZarrV2DataTypeDefinition, CONTEXT) + assert found == () + written = named_fill_value(resolved, value) + if named is UNSET: + assert written is UNSET + return + assert written == named + assert fill_value_problems(resolved, written) == () + + def test_a_float_fill_value_past_the_largest_of_its_width_reads_as_an_infinity() -> None: """A float fill value that is too large for a float of the dtype's width (` None: + resolved, _ = resolve(data_type, DataTypeDefinition, CORE_AND_EXTENSIONS_CONTEXT) + written = named_fill_value(resolved, value) + if named is UNSET: + assert written is UNSET + return + assert _alike(written, named), written + # The named spelling is a valid fill value of the type. + assert fill_value_problems(resolved, written) == () + + +def _names_raising(configuration: EmptyConfiguration, nested: Nested, value: object) -> JSONValue: + raise ValueError("no") + + +def _names_not_json(configuration: EmptyConfiguration, nested: Nested, value: object) -> JSONValue: + return cast("JSONValue", {1, 2}) + + +def test_error_a_named_spelling_that_raises_says_which_data_type_raised_it() -> None: + context = CORE_AND_EXTENSIONS_CONTEXT.union( + ZarrV3Context(data_types=[dataclasses.replace(ACME_POINT, fill_value_named=_names_raising)]) + ) + resolved, _ = resolve("acme.point", DataTypeDefinition, context) + with pytest.raises(ValueError, match="no") as raised: + named_fill_value(resolved, {"x": 1}) + assert raised.value.__notes__ == ["raised by the fill_value_named of 'acme.point'"] + + +def test_error_a_named_spelling_that_is_not_json_is_refused() -> None: + context = CORE_AND_EXTENSIONS_CONTEXT.union( + ZarrV3Context( + data_types=[dataclasses.replace(ACME_POINT, fill_value_named=_names_not_json)] + ) + ) + resolved, _ = resolve("acme.point", DataTypeDefinition, context) + with pytest.raises(TypeError, match="'acme.point': its fill_value_named gives JSON or UNSET"): + named_fill_value(resolved, {"x": 1}) + + @pytest.mark.parametrize( ("name", "low", "high"), [ From d4d05fc1c94784ef2326ae8ca6a67efefe732e8b Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 17:00:51 +0100 Subject: [PATCH 24/27] fix(zarr-metadata): repair a non-finite number wherever the data type names it, and nothing else Review round 1 of c27d46c92: - The repair found names only in a scalar or a list, so an extension data type whose fill value is an object was never repaired, and `struct` declared no `fill_value_named`. The repair now walks lists and objects, and `struct` writes each field as that field's type does. - The repair wrote the hook's whole result while recording only some of its changes. It now writes only the non-finite numbers the hook gives a string for, and its message names the bare token it replaced. - The hook's contract is narrowed to non-finite numbers, which is all the repair writes. - Within each format, the float rule is built from the same function as the hook, so the two cannot drift apart. - docs/validation-rules.md no longer lists the float fill value rule among the rules that need no context; the `DataTypeDefinition` docstring and docs/extensions.md list the hook; the repair docstrings say they run the data type's code. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/docs/extensions.md | 4 +- .../zarr-metadata/docs/validation-rules.md | 10 +-- .../src/zarr_metadata/definition/__init__.py | 19 ++-- .../zarr_metadata/definition/_definition.py | 17 ++-- .../src/zarr_metadata/model/_repair.py | 79 ++++++++++------- .../src/zarr_metadata/v2/data_type/scalar.py | 10 ++- .../src/zarr_metadata/v3/_definition.py | 7 ++ .../src/zarr_metadata/v3/data_type/_float.py | 4 +- .../src/zarr_metadata/v3/data_type/struct.py | 24 ++++++ .../zarr-metadata/tests/model/test_repair.py | 86 ++++++++++++++++--- .../tests/v3/test_fill_values.py | 4 +- 11 files changed, 185 insertions(+), 79 deletions(-) diff --git a/packages/zarr-metadata/docs/extensions.md b/packages/zarr-metadata/docs/extensions.md index 0aa9332c56..ff9e40b26d 100644 --- a/packages/zarr-metadata/docs/extensions.md +++ b/packages/zarr-metadata/docs/extensions.md @@ -104,7 +104,9 @@ definitions that read it, so the model can be pickled only if they can. Other kinds declare more: - A data type declares its fill value (`fill_value`, `fill_value_rules`, - `fill_value_canonical`), and the fill value an array gets when + `fill_value_canonical`), how it writes a non-finite number in a fill + value (`fill_value_named`, such as `"NaN"` for a float, which the + repair readers use), and the fill value an array gets when `create_default` is given none (`fill_value_default`, such as `ConstantFillValue(0)`). It also declares how its values are stored (`storage`), and the array -> bytes codec an array gets when diff --git a/packages/zarr-metadata/docs/validation-rules.md b/packages/zarr-metadata/docs/validation-rules.md index b5dffdbadd..4a0b8986dc 100644 --- a/packages/zarr-metadata/docs/validation-rules.md +++ b/packages/zarr-metadata/docs/validation-rules.md @@ -8,10 +8,6 @@ context. For example: ([`zarr_format`](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#zarr-format) and [`node_type`](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#node-type)), -- a non-finite value spelled as a float's fill value, written by its - name (`"NaN"`, `"Infinity"`, `"-Infinity"`); whether JSON text may - hold a non-finite number anywhere else is left to the JSON routines - that read and write it, - non-negative [dimensions](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#array-metadata-shape), - one @@ -77,9 +73,9 @@ what the package does. accept them wherever a `float` may stand, unless a bound excludes them. `to_key_value` writes them back as bare tokens, which a strict JSON parser rejects. -- One exception: a value spelled as a float data type's fill value is - refused when it is a non-finite number, because the spec writes such a - value by its name. That covers the fill value itself, each component +- One exception, which each data type decides for itself: a float data + type refuses a non-finite number as its fill value, because its spec + writes such a value by its name. That covers the fill value itself, each component of a complex one, a struct's float field, and a codec's scalars spelled the same way, such as `scale_offset`'s `scale` and `offset`. A fill value of a data type that nothing in the context reads is not diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py index 460ba8b25b..e7da9119de 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py @@ -215,15 +215,16 @@ def acme_lz4_rules( gets. `ConstantFillValue(0)` is a default that does not depend on the configuration. `default_fill_value(data_type)` calls it for a data type declaration the scope read. -A type may write some numbers by name: a float writes a `NaN` read from -a document as `"NaN"`, so a number that JSON may hold only as a bare -token means the same to every reader. The rules refuse such a number, -and `fill_value_named` writes each one in a fill value by its name, -returning `UNSET` when there is none, which is what a data type that -does not declare it gets. `named_fill_value(data_type, value)` calls it -for a data type declaration the scope read; the -`non_finite_fill_value` repair uses it, so a data type in the repair's -scope decides what the repair writes. +A type may give a non-finite number, which JSON text holds only as a +bare token, a spelling of its own: a float writes `NaN` as `"NaN"`, so +the value means the same to every reader. Such a type's rules refuse the +bare number, and `fill_value_named` writes each one in a fill value as +the type writes it, returning `UNSET` when there is none, which is what +a data type that does not declare it gets. A struct writes each field +as that field's type does. `named_fill_value(data_type, value)` calls it +for a data type declaration the scope read. The `non_finite_fill_value` +repair uses it and changes only the non-finite numbers, so a data type +in the repair's scope decides what the repair writes. **The simplest spelling.** A declaration without problems has a simplest equivalent spelling, and declarations are compared by it. Each nested declaration is diff --git a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py index 3540a8e419..2015d53645 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -135,7 +135,7 @@ def no_fill_value_default(*_: object) -> UNSET: def no_fill_value_named(*_: object) -> UNSET: - """The named spelling of a fill value for a data type that writes no number by name: `UNSET`, as there is nothing to write.""" + """The named spelling of a fill value for a data type that gives a non-finite number no other spelling: `UNSET`, as there is nothing to write.""" return UNSET @@ -499,9 +499,10 @@ class WithFillValue(Definition[C]): fill value of an array whose document is built without one, as the models' `create_default` builds it. It receives the configuration and the nested declarations, and returns `UNSET` when the type has none. - `fill_value_named` writes each number in a fill value of that shape - that the type writes by name, such as a float's `NaN` as `"NaN"`, by - that name. It receives the same arguments as the rules, and returns + `fill_value_named` writes each non-finite number in a fill value of + that shape (`NaN`, `Infinity` or `-Infinity`, which JSON text holds + only as a bare token) as the type writes it, such as a float's `NaN` + as `"NaN"`. It receives the same arguments as the rules, and returns `UNSET` when the fill value holds no such number. """ @@ -514,7 +515,7 @@ class WithFillValue(Definition[C]): fill_value_default: Callable[[C, Nested], JSONValue | UNSET] = no_fill_value_default """The fill value of an array built without one, such as `0` for `int8`; `UNSET` when the type has none.""" fill_value_named: Callable[[C, Nested, Any], JSONValue | UNSET] = no_fill_value_named - """A fill value of that shape with each number the type writes by name written by that name; `UNSET` when it holds none.""" + """A fill value of that shape with each non-finite number written as the type writes it; `UNSET` when it holds none.""" def _refusal(self) -> str | None: try: @@ -1674,10 +1675,10 @@ def spelled_canonically(data_type: ResolvedDeclaration[F], value: JSONValue) -> def named_fill_value(data_type: ResolvedDeclaration[F], value: object) -> JSONValue | UNSET: - """`value` (a fill value of `data_type`, a data type declaration a scope read) with each number the data type writes by name written by that name, such as a float's `NaN` as `"NaN"`. + """`value` (a fill value of `data_type`, a data type declaration a scope read) with each non-finite number written as the data type writes it, such as a float's `NaN` as `"NaN"`. - The names come from the data type's `fill_value_named`. The result is - `UNSET` when `value` holds no such number, when it is not JSON or not + The spelling comes from the data type's `fill_value_named`. The result + is `UNSET` when `value` holds no such number, when it is not JSON or not of the data type's fill value shape, and when the scope did not read the data type. The data type's function is the extension author's code: its result is checked to be JSON, and an error it raises gets a diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py index 8751a909b5..053d4175dc 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py @@ -17,6 +17,8 @@ from __future__ import annotations +import json +import math from collections.abc import Mapping from dataclasses import dataclass from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeAlias, TypedDict, cast @@ -154,7 +156,9 @@ def repair_node_metadata_v3( new object, which shares its unchanged parts with `value`. A document with none of the bugs is returned as it is, with no repairs. A repair that depends on a data type reads it in `context` - (`CORE_AND_EXTENSIONS_CONTEXT` by default). + (`CORE_AND_EXTENSIONS_CONTEXT` by default), which runs that data + type's definition, so an error in an extension's code is raised here + as the strict read would raise it. """ return _repaired(value, (), scoped(context, CORE_AND_EXTENSIONS_CONTEXT)) @@ -400,7 +404,9 @@ def repair_node_metadata_v2( component of a complex fill value the same way. Each repair is located in `files`, under the name of the file. Content that no repair applies to is left as it is, and `files` is not modified. Files with none of - the bugs are returned as they are, with no repairs. + the bugs are returned as they are, with no repairs. Reading the dtype + runs its definition, so an error in an extension's code is raised here + as the strict read would raise it. """ context = scoped(context, CORE_V2_CONTEXT) if ZARR_V2_ARRAY_METADATA_STORE_KEY not in files: @@ -445,43 +451,50 @@ def _named( at: Loc, repairs: list[Repair], ) -> Mapping[str, object]: - """`document`, an array of either format whose data type is `data_type`, with each number in its fill value that the data type writes by name written by that name. Each name written is added to `repairs`, located under `at`.""" + """`document`, an array of either format whose data type is `data_type`, with each non-finite number in its fill value written as the data type names it (`named_fill_value`). Only those numbers change. Each is added to `repairs`, located under `at`.""" fill_value = document["fill_value"] named = named_fill_value(data_type, fill_value) if named is UNSET: return document - loc = (*at, "fill_value") - written = _names_written(fill_value, named, loc) - if len(written) == 0: + found: list[Repair] = [] + written = _written_by_name(fill_value, named, (*at, "fill_value"), found) + if len(found) == 0: return document - repairs.extend( - _non_finite_repair( - where, name, "a fill value" if where == loc else "a fill value component" + repairs.extend(found) + return {**document, "fill_value": written} + + +def _written_by_name(before: object, after: object, loc: Loc, found: list[Repair]) -> object: + """`before`, a fill value or part of one at `loc`, with each non-finite number that `after` writes as a string at the same place written as that string. Everything else is kept as `before` holds it. Each number written is added to `found`.""" + if isinstance(before, float) and not math.isfinite(before): + if not isinstance(after, str): + return before + found.append( + Repair( + loc, + "non_finite_fill_value", + f'{json.dumps(before)} as a bare token in a fill value, written as "{after}"', + ) ) - for where, name in written - ) - return {**document, "fill_value": named} - - -def _names_written(before: object, after: object, loc: Loc) -> list[tuple[Loc, str]]: - """Each place under `loc` where `after` writes by name, as a string, what `before` holds as a number, with that name.""" - if isinstance(after, str): - return [] if isinstance(before, str) else [(loc, after)] - if not (is_list_or_tuple(before) and is_list_or_tuple(after)) or len(before) != len(after): - return [] - return [ - found - for index, (old, new) in enumerate(zip(before, after, strict=True)) - for found in _names_written(old, new, (*loc, index)) - ] - - -def _non_finite_repair(loc: Loc, name: str, what: str) -> Repair: - return Repair( - loc, - "non_finite_fill_value", - f'{what} of {name} as a bare token, as zarr-python 3.0.0 to 3.0.6 wrote it, written as "{name}"', - ) + return after + count = len(found) + if is_list_or_tuple(before) and is_list_or_tuple(after) and len(before) == len(after): + items = tuple( + _written_by_name(old, new, (*loc, index), found) + for index, (old, new) in enumerate(zip(before, after, strict=True)) + ) + return before if len(found) == count else items + if is_object(before) and is_object(after): + fields = { + key: ( + _written_by_name(old, after[key], (*loc, key), found) + if isinstance(key, str) and key in after + else old + ) + for key, old in before.items() + } + return before if len(found) == count else fields + return before @dataclass(frozen=True, slots=True) diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py index 67f0df91db..dd00b474fb 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py +++ b/packages/zarr-metadata/src/zarr_metadata/v2/data_type/scalar.py @@ -57,8 +57,8 @@ def _float_fill_value_rules( configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2FloatFillValue ) -> Iterator[ValidationProblem]: """The rule for a float fill value: a number that is not finite is written by its name, as the v2 spec spells it.""" - name = _named(value) - if name is not None: + name = _float_named(configuration, nested, value) + if name is not UNSET: yield ValidationProblem( (), f"expected a non-finite value written by its name, {name!r}, got the number {name}", @@ -99,9 +99,11 @@ def _complex_named( def _named(value: ZarrV2FloatFillValue) -> ZarrV2FloatSpecial | None: - """The name the v2 spec gives `value` when it is a number that is not finite: `"NaN"`, `"Infinity"` or `"-Infinity"` + """The name the v2 spec gives `value` when it is a number that is not finite; None for any other value. + + The names are `"NaN"`, `"Infinity"` and `"-Infinity"` (https://github.com/zarr-developers/zarr-specs/blob/fc7dd9c9beb5a50b87f9b08b00bf50fc0048482f/docs/v2/v2.0.rst#L178-L190). - None for any other value. An integer is finite, and may be too large to convert to a float. + An integer is finite, and may be too large to convert to a float. """ if not isinstance(value, float) or math.isfinite(value): return None diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py index ca5ae05908..2972d7cd5a 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py @@ -204,6 +204,13 @@ class DataTypeDefinition(WithFillValue[C], kind=True, format=3): type that does not declare it has one spelling per value: the value as written. + `fill_value_named` writes each non-finite number in a fill value of + that shape as the type writes it, such as a float's `NaN` as `"NaN"`, + and returns `UNSET` when there is none. It receives the same arguments + as the rules. The repair readers use it to undo a writer that wrote + such a number as a bare token. A data type that does not declare it + gives a non-finite number no other spelling. + `storage` declares how the values are stored: in single bytes, in several bytes at a time, or each value in as many bytes as it needs. The `bytes` codec uses this to decide whether the data type it 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 449bf3fa9d..863d2e879f 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 @@ -53,8 +53,8 @@ def __call__( self, configuration: EmptyConfiguration, nested: Nested, value: float | str ) -> Iterator[ValidationProblem]: if not isinstance(value, str): - name = _named(value) - if name is not None: + name = float_fill_value_named(configuration, nested, value) + if name is not UNSET: yield ValidationProblem( (), f"expected a non-finite value written by its name, {name!r}, " 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 9034b80443..82422db27d 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 @@ -14,6 +14,7 @@ Nested, default_fill_value, fill_value_problems, + named_fill_value, spelled_canonically, ) from zarr_metadata.v3._definition import ( @@ -108,6 +109,28 @@ def _fill_value_canonical( return spelled +def _fill_value_named( + configuration: StructConfiguration, nested: Nested, value: StructFillValue +) -> dict[str, JSONValue] | UNSET: + """Return the fill value with each field's fill value written as that field's type writes its non-finite numbers (`named_fill_value`). `UNSET` when no field's type writes any. + + Entries keep their order, and an entry for no field, or for a field + whose type the reading of the struct does not hold, is kept as written. + """ + written: dict[str, JSONValue] = dict(value) + found = False + for index, member in enumerate(configuration["fields"]): + name = member["name"] + field_type = nested.get(("fields", index, "data_type")) + if field_type is None or name not in value: + continue + named = named_fill_value(field_type, value[name]) + if named is not UNSET: + written[name] = named + found = True + return written if found else UNSET + + def _fill_value_default( configuration: StructConfiguration, nested: Nested ) -> dict[str, JSONValue] | UNSET: @@ -157,6 +180,7 @@ def _storage(configuration: StructConfiguration, nested: Nested) -> StorageClass fill_value_default=_fill_value_default, fill_value_rules=_fill_value_rules, fill_value_canonical=_fill_value_canonical, + fill_value_named=_fill_value_named, storage=_storage, number_class="non_numeric", ) diff --git a/packages/zarr-metadata/tests/model/test_repair.py b/packages/zarr-metadata/tests/model/test_repair.py index 01c2f09076..d4723b1286 100644 --- a/packages/zarr-metadata/tests/model/test_repair.py +++ b/packages/zarr-metadata/tests/model/test_repair.py @@ -5,7 +5,8 @@ import copy import json import math -from typing import Any +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, cast import pytest @@ -35,6 +36,9 @@ ZarrV3Context, ) +if TYPE_CHECKING: + from zarr_metadata import JSONValue + ARRAY: dict[str, Any] = dict(ZarrV3ArrayMetadata.create_default(shape=(0, 3)).to_json()) GROUP: dict[str, Any] = {"zarr_format": 3, "node_type": "group"} @@ -320,24 +324,78 @@ def test_repair_v2_node_writes_a_bare_non_finite_fill_value_by_name( """An extension data type that writes a non-finite fill value by name, as the float types do.""" -def test_repair_writes_by_name_what_the_data_type_in_its_scope_names() -> None: - """The `non_finite_fill_value` repair asks the data type, read in the repair's scope, what to write by name, so an extension data type takes part and a type nothing in scope reads is left alone.""" - acme = CORE_AND_EXTENSIONS_CONTEXT.union(ZarrV3Context(data_types=[ACME_HALF])) - value = _consolidated(a={**ARRAY, "data_type": "acme.half", "fill_value": math.nan}) +def _pair_named(configuration: object, nested: object, value: Mapping[str, object]) -> JSONValue: + """Write each non-finite entry as `"NaN"`, and also, beyond the hook's contract, a finite `1.0` as `"one"`.""" + return { + key: "NaN" + if isinstance(item, float) and math.isnan(item) + else "one" + if item == 1.0 + else cast("JSONValue", item) + for key, item in value.items() + } + + +ACME_PAIR = DataTypeDefinition( + name="acme.pair", + configuration=EmptyConfiguration, + fill_value=Mapping[str, float | str], + fill_value_named=_pair_named, +) +"""An extension data type whose fill value is an object.""" + +STRUCT_FLOAT: dict[str, Any] = { + "name": "struct", + "configuration": { + "fields": [ + {"name": "a", "data_type": "int8"}, + {"name": "b", "data_type": "float32"}, + ] + }, +} + + +@pytest.mark.parametrize( + ("data_type", "fill_value", "written", "at"), + [ + ("acme.half", math.nan, "NaN", [()]), + # Only a non-finite number changes, inside an object too. + ("acme.pair", {"x": math.nan, "y": 1.0}, {"x": "NaN", "y": 1.0}, [("x",)]), + (STRUCT_FLOAT, {"a": 1, "b": -math.inf}, {"a": 1, "b": "-Infinity"}, [("b",)]), + # Nothing is written by name for a type nothing in scope reads. + ("acme.unread", math.nan, math.nan, []), + ], + ids=["extension", "object-shaped-extension", "struct-field", "unread"], +) +def test_repair_writes_what_the_data_type_in_its_scope_names( + data_type: JSONValue, fill_value: object, written: object, at: list[tuple[str, ...]] +) -> None: + """The `non_finite_fill_value` repair asks the data type, read in the repair's scope, how to write each non-finite number, so an extension data type and a struct's fields take part.""" + acme = CORE_AND_EXTENSIONS_CONTEXT.union(ZarrV3Context(data_types=[ACME_HALF, ACME_PAIR])) + value = _consolidated(a={**ARRAY, "data_type": data_type, "fill_value": fill_value}) document, made = repair_node_metadata_v3(value, context=acme) - assert json.dumps(document) == json.dumps( - _consolidated(a={**ARRAY, "data_type": "acme.half", "fill_value": "NaN"}) - ) - at = ("consolidated_metadata", "metadata", "a", "fill_value") - assert [(repair.loc, repair.kind) for repair in made] == [(at, "non_finite_fill_value")] + expected = _consolidated(a={**ARRAY, "data_type": data_type, "fill_value": written}) + assert json.dumps(document) == json.dumps(expected) + root = ("consolidated_metadata", "metadata", "a", "fill_value") + assert [(repair.loc, repair.kind) for repair in made] == [ + ((*root, *loc), "non_finite_fill_value") for loc in at + ] assert read_repaired_node_metadata_v3(value, context=acme).repairs == made - assert repair_node_metadata_v3(value) == (value, ()) - # A v2 scope that reads no float dtype leaves a bare NaN for the strict read. + + +def test_repair_reads_the_dtype_in_the_scope_it_is_given() -> None: + """Each v2 repair entry point, and each repaired reader, reads the dtype in its scope: one that reads no float dtype leaves a bare NaN for the strict read.""" no_floats = ZarrV2Context(data_types=[]) - assert repair_node_metadata_v2({".zarray": NAN_ZARRAY}, context=no_floats)[1] == () + files = {".zarray": NAN_ZARRAY} zmetadata = {"zarr_consolidated_format": 1, "metadata": {"a/.zarray": NAN_ZARRAY}} + assert repair_node_metadata_v2(files)[1] != () + assert repair_node_metadata_v2(files, context=no_floats)[1] == () + assert read_repaired_node_metadata_v2(files, context=no_floats).repairs == () + assert repair_consolidated_metadata_v2(zmetadata)[1] != () assert repair_consolidated_metadata_v2(zmetadata, context=no_floats)[1] == () - assert read_repaired_node_metadata_v2({".zarray": NAN_ZARRAY}, context=no_floats).repairs == () + assert read_repaired_consolidated_metadata_v2(zmetadata, context=no_floats).repairs == () + acme = _consolidated(a={**ARRAY, "data_type": "acme.half", "fill_value": math.nan}) + assert repair_node_metadata_v3(acme) == (acme, ()) @pytest.mark.parametrize( diff --git a/packages/zarr-metadata/tests/v3/test_fill_values.py b/packages/zarr-metadata/tests/v3/test_fill_values.py index dd3b043759..11ae038b90 100644 --- a/packages/zarr-metadata/tests/v3/test_fill_values.py +++ b/packages/zarr-metadata/tests/v3/test_fill_values.py @@ -517,6 +517,8 @@ def not_json(configuration: EmptyConfiguration, nested: Nested, value: object) - ("float32", "NaN", UNSET), ("float64", "0x7ff8000000000000", UNSET), ("complex64", [1.0, "Infinity"], UNSET), + (STRUCT, {"a": 1, "b": math.nan}, {"a": 1, "b": "NaN"}), + (STRUCT, {"a": 1, "b": 1.5}, UNSET), # A type that writes no number by name, and one nothing in scope reads. ("int8", 1, UNSET), ("acme.decimal", math.nan, UNSET), @@ -526,7 +528,7 @@ def not_json(configuration: EmptyConfiguration, nested: Nested, value: object) - ], ) def test_a_fill_value_s_named_spelling_writes_each_number_its_type_names( - data_type: str, value: object, named: object + data_type: JSONValue, value: object, named: object ) -> None: resolved, _ = resolve(data_type, DataTypeDefinition, CORE_AND_EXTENSIONS_CONTEXT) written = named_fill_value(resolved, value) From d11b6ce8c26a731632c01cc934561d3d619823a6 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 17:08:44 +0100 Subject: [PATCH 25/27] fix(zarr-metadata): run a data type's named spelling only for a fill value holding a non-finite number Review round 2: the repair ran an extension's `fill_value_named` on every listed array, so a hook that raised made the repaired reader fail on a document the strict reader accepts, which never runs the hook. The repair now first walks the fill value, with its own stack and to the reader's depth, and asks the data type only when it finds a non-finite number. docs/repair.md gives each format's default scope and says the v3 repair also writes a struct's float fields. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/docs/repair.md | 18 ++++++------ .../src/zarr_metadata/model/_repair.py | 28 +++++++++++++++++-- .../zarr-metadata/tests/model/test_repair.py | 18 ++++++++++++ 3 files changed, 54 insertions(+), 10 deletions(-) diff --git a/packages/zarr-metadata/docs/repair.md b/packages/zarr-metadata/docs/repair.md index b32a1ec258..c92d3ec3d0 100644 --- a/packages/zarr-metadata/docs/repair.md +++ b/packages/zarr-metadata/docs/repair.md @@ -33,16 +33,18 @@ Each one works in three steps: zarr-python 3.0.0 to 3.0.6 wrote it. The repair writes the string the [v2 spec](https://zarr-specs.readthedocs.io/en/latest/v2/v2.0.html#fill-value-encoding) uses, such as `"NaN"`. -- **A bare non-finite float or complex fill value in a v3 group's - consolidated metadata.** zarr-python 3.0.0 to 3.0.6 wrote it. The repair - writes the string the +- **A bare non-finite number in a fill value in a v3 group's + consolidated metadata.** zarr-python 3.0.0 to 3.0.6 wrote it for a float + or complex array. The repair writes the string the [v3 spec](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/data-types/index.html#permitted-fill-values) - uses, such as `"NaN"`. + uses, such as `"NaN"`, also in a struct's float fields. -The two fill value repairs ask the array's data type what to write. The -data type is read in the scope the repair is given (`context`, the core -scope by default), and its `fill_value_named` writes each number it -names by that name. So an extension data type that declares +The two fill value repairs ask the array's data type what to write, and +only for a fill value that holds a non-finite number. The data type is +read in the scope the repair is given (`context`; by default +`CORE_AND_EXTENSIONS_CONTEXT` for v3 and `CORE_V2_CONTEXT` for v2), and +its `fill_value_named` writes each non-finite number as the type writes +it. Only those numbers change. So an extension data type that declares `fill_value_named` is repaired too, and a data type nothing in the scope reads is left for the strict read. diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py index 053d4175dc..3acaea51ed 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py @@ -158,7 +158,9 @@ def repair_node_metadata_v3( that depends on a data type reads it in `context` (`CORE_AND_EXTENSIONS_CONTEXT` by default), which runs that data type's definition, so an error in an extension's code is raised here - as the strict read would raise it. + as the strict read would raise it. Its `fill_value_named`, which the + strict read does not run, runs only for a fill value that holds a + non-finite number. """ return _repaired(value, (), scoped(context, CORE_AND_EXTENSIONS_CONTEXT)) @@ -406,7 +408,9 @@ def repair_node_metadata_v2( to is left as it is, and `files` is not modified. Files with none of the bugs are returned as they are, with no repairs. Reading the dtype runs its definition, so an error in an extension's code is raised here - as the strict read would raise it. + as the strict read would raise it. Its `fill_value_named`, which the + strict read does not run, runs only for a fill value that holds a + non-finite number. """ context = scoped(context, CORE_V2_CONTEXT) if ZARR_V2_ARRAY_METADATA_STORE_KEY not in files: @@ -453,6 +457,10 @@ def _named( ) -> Mapping[str, object]: """`document`, an array of either format whose data type is `data_type`, with each non-finite number in its fill value written as the data type names it (`named_fill_value`). Only those numbers change. Each is added to `repairs`, located under `at`.""" fill_value = document["fill_value"] + if not _holds_non_finite(fill_value): + # The data type's code is not run on a fill value it has nothing to + # write for, so the repair reads such a document as the strict read does. + return document named = named_fill_value(data_type, fill_value) if named is UNSET: return document @@ -464,6 +472,22 @@ def _named( return {**document, "fill_value": written} +def _holds_non_finite(value: object) -> bool: + """Whether `value` holds a non-finite number in an array or object at most `JSON_DEPTH` levels down. The walk keeps its own stack, so a deep or cyclic value does not exhaust the interpreter's.""" + stack: list[tuple[object, int]] = [(value, 0)] + while len(stack) != 0: + item, depth = stack.pop() + if isinstance(item, float) and not math.isfinite(item): + return True + if depth >= JSON_DEPTH: + continue + if is_list_or_tuple(item): + stack.extend((inner, depth + 1) for inner in item) + elif is_object(item): + stack.extend((inner, depth + 1) for inner in item.values()) + return False + + def _written_by_name(before: object, after: object, loc: Loc, found: list[Repair]) -> object: """`before`, a fill value or part of one at `loc`, with each non-finite number that `after` writes as a string at the same place written as that string. Everything else is kept as `before` holds it. Each number written is added to `found`.""" if isinstance(before, float) and not math.isfinite(before): diff --git a/packages/zarr-metadata/tests/model/test_repair.py b/packages/zarr-metadata/tests/model/test_repair.py index d4723b1286..e7a5aad873 100644 --- a/packages/zarr-metadata/tests/model/test_repair.py +++ b/packages/zarr-metadata/tests/model/test_repair.py @@ -3,6 +3,7 @@ from __future__ import annotations import copy +import dataclasses import json import math from collections.abc import Mapping @@ -383,6 +384,23 @@ def test_repair_writes_what_the_data_type_in_its_scope_names( assert read_repaired_node_metadata_v3(value, context=acme).repairs == made +def _named_raising(configuration: object, nested: object, value: object) -> JSONValue: + raise ValueError("hook bug") + + +def test_repair_runs_no_named_spelling_for_a_fill_value_without_a_non_finite_number() -> None: + """The strict read never runs `fill_value_named`, so the repaired read of a document with no non-finite number does not run it either, and reads that document as the strict read does.""" + acme = CORE_AND_EXTENSIONS_CONTEXT.union( + ZarrV3Context(data_types=[dataclasses.replace(ACME_HALF, fill_value_named=_named_raising)]) + ) + value = _consolidated(a={**ARRAY, "data_type": "acme.half", "fill_value": 1.0}) + assert read_repaired_node_metadata_v3(value, context=acme).repairs == () + assert read_node_metadata_v3(value, context=acme).problems == () + named = _consolidated(a={**ARRAY, "data_type": "acme.half", "fill_value": math.nan}) + with pytest.raises(ValueError, match="hook bug"): + repair_node_metadata_v3(named, context=acme) + + def test_repair_reads_the_dtype_in_the_scope_it_is_given() -> None: """Each v2 repair entry point, and each repaired reader, reads the dtype in its scope: one that reads no float dtype leaves a bare NaN for the strict read.""" no_floats = ZarrV2Context(data_types=[]) From 08d0cf7c3055daa4b30854f48b9a69734a252a24 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 17:15:46 +0100 Subject: [PATCH 26/27] fix(zarr-metadata): repair only a fill value the data type's rules refuse Review round 3: the pre-walk skipped the hook only for a fill value with no non-finite number, so a data type whose rules accept a bare `NaN` still had its `fill_value_named` run on a document whose read accepts it. The repair now checks the fill value against the data type's rules first, as reading the document does, and runs the hook only when they report a problem. The pre-walk is gone; the rules check costs more than it did on a large fill value (about 0.3 ms per listed array with a 1,024-element fill value), and nothing on a scalar one. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-metadata/docs/repair.md | 2 +- .../src/zarr_metadata/model/_repair.py | 31 ++++------------ .../src/zarr_metadata/v3/_definition.py | 4 +-- .../zarr-metadata/tests/model/test_repair.py | 35 ++++++++++++++----- 4 files changed, 36 insertions(+), 36 deletions(-) diff --git a/packages/zarr-metadata/docs/repair.md b/packages/zarr-metadata/docs/repair.md index c92d3ec3d0..2161b6d5a9 100644 --- a/packages/zarr-metadata/docs/repair.md +++ b/packages/zarr-metadata/docs/repair.md @@ -40,7 +40,7 @@ Each one works in three steps: uses, such as `"NaN"`, also in a struct's float fields. The two fill value repairs ask the array's data type what to write, and -only for a fill value that holds a non-finite number. The data type is +only for a fill value the data type's rules refuse. The data type is read in the scope the repair is given (`context`; by default `CORE_AND_EXTENSIONS_CONTEXT` for v3 and `CORE_V2_CONTEXT` for v2), and its `fill_value_named` writes each non-finite number as the type writes diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py index 3acaea51ed..b6215adfa9 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py @@ -41,6 +41,7 @@ ) from zarr_metadata.definition._definition import ( ResolvedDeclaration, + fill_value_problems, named_fill_value, resolve, ) @@ -159,8 +160,7 @@ def repair_node_metadata_v3( (`CORE_AND_EXTENSIONS_CONTEXT` by default), which runs that data type's definition, so an error in an extension's code is raised here as the strict read would raise it. Its `fill_value_named`, which the - strict read does not run, runs only for a fill value that holds a - non-finite number. + strict read does not run, runs only for a fill value its rules refuse. """ return _repaired(value, (), scoped(context, CORE_AND_EXTENSIONS_CONTEXT)) @@ -409,8 +409,7 @@ def repair_node_metadata_v2( the bugs are returned as they are, with no repairs. Reading the dtype runs its definition, so an error in an extension's code is raised here as the strict read would raise it. Its `fill_value_named`, which the - strict read does not run, runs only for a fill value that holds a - non-finite number. + strict read does not run, runs only for a fill value its rules refuse. """ context = scoped(context, CORE_V2_CONTEXT) if ZARR_V2_ARRAY_METADATA_STORE_KEY not in files: @@ -455,11 +454,11 @@ def _named( at: Loc, repairs: list[Repair], ) -> Mapping[str, object]: - """`document`, an array of either format whose data type is `data_type`, with each non-finite number in its fill value written as the data type names it (`named_fill_value`). Only those numbers change. Each is added to `repairs`, located under `at`.""" + """`document`, an array of either format whose data type is `data_type`, with each non-finite number in its fill value written as the data type names it (`named_fill_value`), when the data type's rules refuse the fill value. Only those numbers change. Each is added to `repairs`, located under `at`.""" fill_value = document["fill_value"] - if not _holds_non_finite(fill_value): - # The data type's code is not run on a fill value it has nothing to - # write for, so the repair reads such a document as the strict read does. + if len(fill_value_problems(data_type, fill_value)) == 0: + # A fill value the strict read accepts is left alone, and the data + # type's `fill_value_named`, which the strict read never runs, is not run. return document named = named_fill_value(data_type, fill_value) if named is UNSET: @@ -472,22 +471,6 @@ def _named( return {**document, "fill_value": written} -def _holds_non_finite(value: object) -> bool: - """Whether `value` holds a non-finite number in an array or object at most `JSON_DEPTH` levels down. The walk keeps its own stack, so a deep or cyclic value does not exhaust the interpreter's.""" - stack: list[tuple[object, int]] = [(value, 0)] - while len(stack) != 0: - item, depth = stack.pop() - if isinstance(item, float) and not math.isfinite(item): - return True - if depth >= JSON_DEPTH: - continue - if is_list_or_tuple(item): - stack.extend((inner, depth + 1) for inner in item) - elif is_object(item): - stack.extend((inner, depth + 1) for inner in item.values()) - return False - - def _written_by_name(before: object, after: object, loc: Loc, found: list[Repair]) -> object: """`before`, a fill value or part of one at `loc`, with each non-finite number that `after` writes as a string at the same place written as that string. Everything else is kept as `before` holds it. Each number written is added to `found`.""" if isinstance(before, float) and not math.isfinite(before): diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py index 2972d7cd5a..cec95ed07f 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py @@ -207,8 +207,8 @@ class DataTypeDefinition(WithFillValue[C], kind=True, format=3): `fill_value_named` writes each non-finite number in a fill value of that shape as the type writes it, such as a float's `NaN` as `"NaN"`, and returns `UNSET` when there is none. It receives the same arguments - as the rules. The repair readers use it to undo a writer that wrote - such a number as a bare token. A data type that does not declare it + as the rules. The repair readers use it, for a fill value the rules + refuse, to undo a writer that wrote such a number as a bare token. A data type that does not declare it gives a non-finite number no other spelling. `storage` declares how the values are stored: in single bytes, in diff --git a/packages/zarr-metadata/tests/model/test_repair.py b/packages/zarr-metadata/tests/model/test_repair.py index e7a5aad873..20ac81b427 100644 --- a/packages/zarr-metadata/tests/model/test_repair.py +++ b/packages/zarr-metadata/tests/model/test_repair.py @@ -6,12 +6,14 @@ import dataclasses import json import math -from collections.abc import Mapping +from collections.abc import Iterator, Mapping from typing import TYPE_CHECKING, Any, cast import pytest +from zarr_metadata import ValidationProblem from zarr_metadata.definition import EmptyConfiguration +from zarr_metadata.definition._definition import no_rules from zarr_metadata.model import ( ZarrV2ArrayMetadata, ZarrV2ConsolidatedMetadata, @@ -316,10 +318,22 @@ def test_repair_v2_node_writes_a_bare_non_finite_fill_value_by_name( assert document is files +def _refuses_non_finite( + configuration: object, nested: object, value: object +) -> Iterator[ValidationProblem]: + """Refuse each non-finite number in `value`, a number or an object of numbers, as the float types do.""" + items = list(value.items()) if isinstance(value, Mapping) else [(None, value)] + for key, item in items: + if isinstance(item, float) and not math.isfinite(item): + loc = () if key is None else (key,) + yield ValidationProblem(loc, "expected the name", "invalid_value") + + ACME_HALF = DataTypeDefinition( name="acme.half", configuration=EmptyConfiguration, fill_value=float | str, + fill_value_rules=_refuses_non_finite, fill_value_named=float_fill_value_named, ) """An extension data type that writes a non-finite fill value by name, as the float types do.""" @@ -341,6 +355,7 @@ def _pair_named(configuration: object, nested: object, value: Mapping[str, objec name="acme.pair", configuration=EmptyConfiguration, fill_value=Mapping[str, float | str], + fill_value_rules=_refuses_non_finite, fill_value_named=_pair_named, ) """An extension data type whose fill value is an object.""" @@ -388,14 +403,16 @@ def _named_raising(configuration: object, nested: object, value: object) -> JSON raise ValueError("hook bug") -def test_repair_runs_no_named_spelling_for_a_fill_value_without_a_non_finite_number() -> None: - """The strict read never runs `fill_value_named`, so the repaired read of a document with no non-finite number does not run it either, and reads that document as the strict read does.""" - acme = CORE_AND_EXTENSIONS_CONTEXT.union( - ZarrV3Context(data_types=[dataclasses.replace(ACME_HALF, fill_value_named=_named_raising)]) - ) - value = _consolidated(a={**ARRAY, "data_type": "acme.half", "fill_value": 1.0}) - assert read_repaired_node_metadata_v3(value, context=acme).repairs == () - assert read_node_metadata_v3(value, context=acme).problems == () +def test_repair_runs_no_named_spelling_for_a_fill_value_the_strict_read_accepts() -> None: + """The strict read never runs `fill_value_named`, so the repair runs it only for a fill value the data type's rules refuse, and reads any other document as the strict read does. A data type whose rules allow a bare `NaN` keeps it.""" + raising = dataclasses.replace(ACME_HALF, fill_value_named=_named_raising) + allowing = dataclasses.replace(raising, fill_value_rules=no_rules) + for definition, fill_value in ((raising, 1.0), (allowing, math.nan)): + acme = CORE_AND_EXTENSIONS_CONTEXT.union(ZarrV3Context(data_types=[definition])) + value = _consolidated(a={**ARRAY, "data_type": "acme.half", "fill_value": fill_value}) + assert read_node_metadata_v3(value, context=acme).problems == () + assert read_repaired_node_metadata_v3(value, context=acme).repairs == () + acme = CORE_AND_EXTENSIONS_CONTEXT.union(ZarrV3Context(data_types=[raising])) named = _consolidated(a={**ARRAY, "data_type": "acme.half", "fill_value": math.nan}) with pytest.raises(ValueError, match="hook bug"): repair_node_metadata_v3(named, context=acme) From e9f017a3673be508d3def1b2358a25604f06f67b Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 17:23:45 +0100 Subject: [PATCH 27/27] fix(zarr-metadata): name a struct field only when its own type refuses it, and locate rule errors in a repair Review round 4 (no serious findings): - The struct hook named every non-finite field once any field was refused, including a field whose own type accepts a bare `NaN`. It now skips a field its type accepts. - An error raised by a data type's rules during a repair now names the listed entry it was reading. - The repair docstrings compared the repair with the group's strict read, which never reads the documents its consolidated metadata lists. They now compare it with reading those documents, which runs the same data type code. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../src/zarr_metadata/model/_repair.py | 19 ++++++++++------- .../src/zarr_metadata/v3/_definition.py | 3 ++- .../src/zarr_metadata/v3/data_type/struct.py | 11 +++++++--- .../zarr-metadata/tests/model/test_repair.py | 21 +++++++++++++++++-- 4 files changed, 40 insertions(+), 14 deletions(-) diff --git a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py index b6215adfa9..36920c5987 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py @@ -157,10 +157,12 @@ def repair_node_metadata_v3( new object, which shares its unchanged parts with `value`. A document with none of the bugs is returned as it is, with no repairs. A repair that depends on a data type reads it in `context` - (`CORE_AND_EXTENSIONS_CONTEXT` by default), which runs that data - type's definition, so an error in an extension's code is raised here - as the strict read would raise it. Its `fill_value_named`, which the - strict read does not run, runs only for a fill value its rules refuse. + (`CORE_AND_EXTENSIONS_CONTEXT` by default), and checks the fill + value against it, as reading the listed documents + (`read_consolidated_metadata_v3`) does, so an error in an extension's + code is raised here as that read would raise it. The data type's + `fill_value_named`, which no read runs, runs only for a fill value its + rules refuse. """ return _repaired(value, (), scoped(context, CORE_AND_EXTENSIONS_CONTEXT)) @@ -407,9 +409,10 @@ def repair_node_metadata_v2( in `files`, under the name of the file. Content that no repair applies to is left as it is, and `files` is not modified. Files with none of the bugs are returned as they are, with no repairs. Reading the dtype - runs its definition, so an error in an extension's code is raised here - as the strict read would raise it. Its `fill_value_named`, which the - strict read does not run, runs only for a fill value its rules refuse. + and checking the fill value against it run its definition, as the + strict read does, so an error in an extension's code is raised here as + that read would raise it. Its `fill_value_named`, which no read runs, + runs only for a fill value its rules refuse. """ context = scoped(context, CORE_V2_CONTEXT) if ZARR_V2_ARRAY_METADATA_STORE_KEY not in files: @@ -456,7 +459,7 @@ def _named( ) -> Mapping[str, object]: """`document`, an array of either format whose data type is `data_type`, with each non-finite number in its fill value written as the data type names it (`named_fill_value`), when the data type's rules refuse the fill value. Only those numbers change. Each is added to `repairs`, located under `at`.""" fill_value = document["fill_value"] - if len(fill_value_problems(data_type, fill_value)) == 0: + if len(fill_value_problems(data_type, fill_value, (*at, "fill_value"))) == 0: # A fill value the strict read accepts is left alone, and the data # type's `fill_value_named`, which the strict read never runs, is not run. return document diff --git a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py index cec95ed07f..8bdaa304ca 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py @@ -208,7 +208,8 @@ class DataTypeDefinition(WithFillValue[C], kind=True, format=3): that shape as the type writes it, such as a float's `NaN` as `"NaN"`, and returns `UNSET` when there is none. It receives the same arguments as the rules. The repair readers use it, for a fill value the rules - refuse, to undo a writer that wrote such a number as a bare token. A data type that does not declare it + refuse, to undo a writer that wrote such a number as a bare + token. A data type that does not declare it gives a non-finite number no other spelling. `storage` declares how the values are stored: in single bytes, in 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 82422db27d..982df071c9 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 @@ -114,15 +114,20 @@ def _fill_value_named( ) -> dict[str, JSONValue] | UNSET: """Return the fill value with each field's fill value written as that field's type writes its non-finite numbers (`named_fill_value`). `UNSET` when no field's type writes any. - Entries keep their order, and an entry for no field, or for a field - whose type the reading of the struct does not hold, is kept as written. + Entries keep their order. An entry for no field, for a field whose + type the reading of the struct does not hold, or that its field's type + accepts as written, is kept as written. """ written: dict[str, JSONValue] = dict(value) found = False for index, member in enumerate(configuration["fields"]): name = member["name"] field_type = nested.get(("fields", index, "data_type")) - if field_type is None or name not in value: + if ( + field_type is None + or name not in value + or len(fill_value_problems(field_type, value[name])) == 0 + ): continue named = named_fill_value(field_type, value[name]) if named is not UNSET: diff --git a/packages/zarr-metadata/tests/model/test_repair.py b/packages/zarr-metadata/tests/model/test_repair.py index 20ac81b427..b70d24b8e7 100644 --- a/packages/zarr-metadata/tests/model/test_repair.py +++ b/packages/zarr-metadata/tests/model/test_repair.py @@ -360,6 +360,19 @@ def _pair_named(configuration: object, nested: object, value: Mapping[str, objec ) """An extension data type whose fill value is an object.""" +ACME_LAX = dataclasses.replace(ACME_HALF, name="acme.lax", fill_value_rules=no_rules) +"""An extension data type whose rules accept a bare `NaN`.""" + +STRUCT_LAX: dict[str, Any] = { + "name": "struct", + "configuration": { + "fields": [ + {"name": "h", "data_type": "acme.lax"}, + {"name": "x", "data_type": "float64"}, + ] + }, +} + STRUCT_FLOAT: dict[str, Any] = { "name": "struct", "configuration": { @@ -378,16 +391,20 @@ def _pair_named(configuration: object, nested: object, value: Mapping[str, objec # Only a non-finite number changes, inside an object too. ("acme.pair", {"x": math.nan, "y": 1.0}, {"x": "NaN", "y": 1.0}, [("x",)]), (STRUCT_FLOAT, {"a": 1, "b": -math.inf}, {"a": 1, "b": "-Infinity"}, [("b",)]), + # A field whose own type accepts a bare `NaN` keeps it. + (STRUCT_LAX, {"h": math.nan, "x": math.nan}, {"h": math.nan, "x": "NaN"}, [("x",)]), # Nothing is written by name for a type nothing in scope reads. ("acme.unread", math.nan, math.nan, []), ], - ids=["extension", "object-shaped-extension", "struct-field", "unread"], + ids=["extension", "object-shaped-extension", "struct-field", "struct-lax-field", "unread"], ) def test_repair_writes_what_the_data_type_in_its_scope_names( data_type: JSONValue, fill_value: object, written: object, at: list[tuple[str, ...]] ) -> None: """The `non_finite_fill_value` repair asks the data type, read in the repair's scope, how to write each non-finite number, so an extension data type and a struct's fields take part.""" - acme = CORE_AND_EXTENSIONS_CONTEXT.union(ZarrV3Context(data_types=[ACME_HALF, ACME_PAIR])) + acme = CORE_AND_EXTENSIONS_CONTEXT.union( + ZarrV3Context(data_types=[ACME_HALF, ACME_PAIR, ACME_LAX]) + ) value = _consolidated(a={**ARRAY, "data_type": data_type, "fill_value": fill_value}) document, made = repair_node_metadata_v3(value, context=acme) expected = _consolidated(a={**ARRAY, "data_type": data_type, "fill_value": written})