diff --git a/packages/zarr-metadata/changes/493.feature.md b/packages/zarr-metadata/changes/493.feature.md new file mode 100644 index 0000000000..04a52f306d --- /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 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/changes/493.removal.md b/packages/zarr-metadata/changes/493.removal.md new file mode 100644 index 0000000000..42e0e4d47f --- /dev/null +++ b/packages/zarr-metadata/changes/493.removal.md @@ -0,0 +1 @@ +`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/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/repair.md b/packages/zarr-metadata/docs/repair.md index f4f197e40e..2161b6d5a9 100644 --- a/packages/zarr-metadata/docs/repair.md +++ b/packages/zarr-metadata/docs/repair.md @@ -33,11 +33,20 @@ 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, and +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 +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. ## Bugs the repair readers do not undo diff --git a/packages/zarr-metadata/docs/validation-rules.md b/packages/zarr-metadata/docs/validation-rules.md index 5a0b194c21..4a0b8986dc 100644 --- a/packages/zarr-metadata/docs/validation-rules.md +++ b/packages/zarr-metadata/docs/validation-rules.md @@ -8,8 +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)), -- finite JSON numbers, except in `attributes` and in members that nothing - in the context reads, - non-negative [dimensions](https://zarr-specs.readthedocs.io/en/v3.1.0/v3/core/index.html#array-metadata-shape), - one @@ -65,18 +63,23 @@ 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 `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, 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 + 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/_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 f55081b1f6..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. - """ - 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. + 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=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): @@ -519,13 +504,9 @@ 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) + member, found = _refine(item, (*loc, key)) found_in_members.extend(found) if len(found) == 0: members[key] = member @@ -533,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 ( @@ -591,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. @@ -610,6 +586,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): @@ -698,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 @@ -847,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 b774ddd586..c145c15c3c 100644 --- a/packages/zarr-metadata/src/zarr_metadata/_typed_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/_typed_json.py @@ -71,16 +71,18 @@ 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, choices, copied, - is_canonical_json, - is_json, + is_array, is_list_or_tuple, is_object, listed, + nested_past_the_levels, + non_string_key, outside_of, refine_json, shown, @@ -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,50 @@ 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 +# 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 cls is float or value is None: + return True + 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)}") @@ -622,8 +659,15 @@ 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) -_USER_JSON: Final = _scalar("a JSON value", lambda value: is_canonical_json(value, finite=False)) + + +def _json(value: object, loc: Loc) -> Parsed: + """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 + + +_JSON: Final[Parser] = _json def one_of(allowed: tuple[object, ...]) -> Parser: @@ -637,6 +681,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, () @@ -648,8 +697,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] = [] @@ -666,8 +718,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)}") @@ -756,6 +811,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)),) @@ -787,17 +845,23 @@ 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] = [] 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 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. + found.extend(refine_json(entry, (*loc, key))[1]) continue parsed[key], problems = extra(entry, (*loc, key)) found.extend(problems) @@ -824,12 +888,15 @@ 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] = [] 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 @@ -1315,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) @@ -1502,9 +1567,9 @@ 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), + 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 @@ -1516,10 +1581,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/__init__.py b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py index df2f4905a7..e7da9119de 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/__init__.py @@ -88,8 +88,11 @@ 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. 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 +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 @@ -163,7 +166,10 @@ def acme_lz4_rules( 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, -`tuple[Annotated[int, Ge(1)], ...]` bounds each element. An integer's +`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 @@ -209,6 +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 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 @@ -271,9 +287,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. """ @@ -293,6 +308,7 @@ def acme_lz4_rules( configuration_of, default_fill_value, fill_value_problems, + named_fill_value, resolve, with_problems, ) @@ -321,6 +337,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 f59fea98a4..2015d53645 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_definition.py @@ -60,7 +60,11 @@ from typing_extensions import TypeAliasType, TypeVar, is_typeddict -from zarr_metadata._common import EmptyConfiguration, JSONValue, ZarrV3NamedConfigJSON +from zarr_metadata._common import ( + EmptyConfiguration, + JSONValue, + ZarrV3NamedConfigJSON, +) from zarr_metadata._json import ( Problems, ValidationProblem, @@ -70,10 +74,10 @@ is_tuple, json_text, refine_json, - refine_user_data, said, shown, with_input, + within, ) from zarr_metadata._sentinel import UNSET from zarr_metadata._typed_json import ( @@ -130,6 +134,11 @@ def no_fill_value_default(*_: object) -> UNSET: return UNSET +def no_fill_value_named(*_: object) -> UNSET: + """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 + + @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`. @@ -266,9 +275,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: @@ -287,9 +296,30 @@ 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. 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_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, 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, 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: @@ -369,10 +399,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.""" @@ -385,9 +411,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]: @@ -475,6 +499,11 @@ 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 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. """ fill_value: object = JSONValue @@ -485,6 +514,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 non-finite number written as the type writes it; `UNSET` when it holds none.""" def _refusal(self) -> str | None: try: @@ -586,40 +617,44 @@ 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 + 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. """ loc: Loc kind: type[Definition[Any]] - json: JSONValue + 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 problem that keeps a definition from reading the declaration at all, as its kind finds them (`_refined`), 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, 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.""" - 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 = self.kind._refined(value, loc, None) + 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: @@ -701,26 +736,36 @@ class _Checker: nests: bool -@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] = [] +class _Meeting: + """The leaf of a checker: `_declaration`, recording whether the annotation it compiles holds a declaration anywhere.""" - def leaf(annotation: object) -> Parser | None: + def __init__(self) -> None: + self.met = False + + def __call__(self, annotation: object) -> Parser | None: found = _declaration(annotation) - if found is not None: - met.append(annotation) + self.met = self.met or found is not None return found - return _Checker(parser(shape, leaf), len(met) != 0) +@functools.cache +def _checker(shape: type) -> _Checker: + """The checker for a TypedDict, compiled once. Raises `TypeError` naming any part that no checker reads.""" + meeting = _Meeting() + parse = parser(shape, meeting) + return _Checker(parse, meeting.met) -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 + +@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 _typed( @@ -749,14 +794,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} @@ -851,13 +896,44 @@ 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.""" - return _located(declaration.loc, declaration.kind._envelope_problems(declaration.json)) + """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 + found = declaration.kind._envelope_problems(_as_read(declaration), declaration.loc) + return _located(declaration.loc, found) + + +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 _explained( + declaration.kind, + declaration.written, + declaration.json, + declaration.loc, + (*_envelope(declaration), *unread), + ) + + +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 + 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. @@ -867,21 +943,105 @@ 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 unless `finite` is false, for a configuration that - holds user data; the TypedDict still decides where such a number may - be. + 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. 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 +@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, 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.""" + + +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. + + 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, 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 + written. + """ + keys = typeddict_keys(shape) + extension_fields: dict[str, object] = {} + 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 + 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: _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 its kind refines + declarations, so it is read without being refined again. + """ + resolved, found = resolve_refined( + declaration.written, + declaration.json, + declaration.problems, + declaration.kind, + context, + declaration.loc, + ) + return resolved, within((*found, *_sized(declaration, resolved)), at) + + def named_configuration( value: object, ) -> tuple[str | None, Mapping[str, object] | None, Problems]: @@ -934,7 +1094,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 (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 @@ -1514,13 +1674,52 @@ 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 non-finite number written as the data type writes it, such as a float's `NaN` as `"NaN"`. + + 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 + 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]: """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. @@ -1590,18 +1789,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) @@ -1616,53 +1817,69 @@ 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) - return resolved, (*envelope, *found) + read = data if json is UNSET else json + envelope = _located(loc, kind._envelope_problems(read, loc)) + resolved, found = _read(read, json, kind, context, loc) + 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( - 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 = _typed(definition.configuration, {} if given is None else 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 @@ -1673,19 +1890,31 @@ 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: + # 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, UNSET, placed.problems, placed.kind, context, placed.loc + ) + else: + 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 - # 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)) + 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. + # 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) configuration = ( cast( @@ -1701,13 +1930,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) @@ -1747,13 +1976,37 @@ def _in_document( def _named(declaration: _NestedDeclaration) -> bool: - """Whether a nested declaration has a name, and its configuration (if any) is an object.""" + """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. 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 _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, + data: object, + json: JSONValue | UNSET, name: str, kind: type[Definition[Any]], definition: Definition[Any], @@ -1768,11 +2021,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 @@ -1808,11 +2057,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 @@ -1947,6 +2202,7 @@ def _replaced(value: JSONValue, path: Loc, new: JSONValue) -> JSONValue: "Problems", "RefusedDeclaration", "ResolvedDeclaration", + "TypedDocument", "UnclaimedDeclaration", "WithFillValue", "as_kind", @@ -1969,14 +2225,18 @@ def _replaced(value: JSONValue, path: Loc, new: JSONValue) -> JSONValue: "item_at", "kind_of", "named_configuration", + "named_fill_value", + "no_fill_value_named", "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/definition/_envelope.py b/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py index b47659068d..165c79741c 100644 --- a/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py +++ b/packages/zarr-metadata/src/zarr_metadata/definition/_envelope.py @@ -6,9 +6,12 @@ import functools import re +from collections.abc import Mapping 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, within +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.""" @@ -58,69 +61,56 @@ 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: 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 _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) +"""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 + 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. - 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. `loc` is where the declaration is, from the + root, so depth is counted from there; each problem is located in the + declaration. """ - 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, loc) + problems = list(within(found, loc)) + 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/src/zarr_metadata/model/_array_v3.py b/packages/zarr-metadata/src/zarr_metadata/model/_array_v3.py index 2ea2af7ccb..9bb864522b 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, ) @@ -92,52 +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 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 +188,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( + typed.extension_fields, 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[len(at)]) + if len(declaration.loc) == len(at) + 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 +235,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 +244,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,56 +260,44 @@ 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={ + key: members[key] if key in members else extra_fields[key] + for key in cast("Mapping[str, object]", value) + }, ) - return reading, members def read_extra_fields_v3( - doc: Mapping[object, object], + fields: Mapping[str, object], 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 `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 `doc`. 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 - `json` module reads it. + 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. 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]] = {} 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 - 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] @@ -594,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_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 9c5d9dc006..aa887af2ae 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_group_v3.py @@ -26,20 +26,26 @@ is_object, json_text, nested_past_the_levels, + non_string_key, not_an_object, outside_of, prefixed, - refine_user_data, + refine_json, said, shown, - shown_key, with_input, within, ) 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, 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 +60,6 @@ ZarrV3ArrayMetadataReading, array_key_of, extra_fields_key, - members_past_the_levels, must_understand_subset, no_extra_fields, read_array_metadata_v3, @@ -66,7 +71,6 @@ from zarr_metadata.model._keyed import Keyed from zarr_metadata.model._shared import ( StoreKey, - attributes_of, check_literal, load_store_json, located_conflicts, @@ -74,7 +78,6 @@ missing_keys, reading_of, unclaimed_declarations_of, - unexpected_keys, ) from zarr_metadata.v3._common import ( ZARR_V3_NODE_TYPE, @@ -90,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 @@ -104,13 +108,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. @@ -271,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)} @@ -949,61 +944,49 @@ 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( + typed.extension_fields, 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, + # 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) } - document = {key: refined[key] for key in cast("Mapping[str, object]", doc)} + if len(found) == 0 + else None + ) 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. 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)) - 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( @@ -1044,7 +1027,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) @@ -1119,7 +1102,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] = {} @@ -1134,11 +1117,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/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/model/_repair.py b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py index 679a584fc8..36920c5987 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_repair.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_repair.py @@ -17,10 +17,11 @@ from __future__ import annotations +import json import math 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 @@ -33,10 +34,17 @@ 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 ( + ResolvedDeclaration, + fill_value_problems, + named_fill_value, + resolve, +) from zarr_metadata.model._group_v2 import ( ZarrV2ConsolidatedMetadataReading, ZarrV2NodeMetadataReading, @@ -44,10 +52,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: @@ -124,17 +134,20 @@ 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 - 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. + `Infinity` or `-Infinity`. The spec writes these as + 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 +155,19 @@ 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), 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, ()) + 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 +178,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 +255,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 +270,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 +300,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 +313,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 +343,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,116 +375,136 @@ 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 - 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 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. Reading the dtype + 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: 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 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 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: + 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 - names = [_non_finite_name(component) for component in fill_value] - if all(name is None for name in names): + named = named_fill_value(data_type, fill_value) + if named is UNSET: 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) - ) - 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, - "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}"', - ) + found: list[Repair] = [] + written = _written_by_name(fill_value, named, (*at, "fill_value"), found) + if len(found) == 0: + return document + 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}"', + ) + ) + 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) @@ -483,7 +528,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 ) @@ -511,7 +556,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/model/_shared.py b/packages/zarr-metadata/src/zarr_metadata/model/_shared.py index a946c4a608..61568224e1 100644 --- a/packages/zarr-metadata/src/zarr_metadata/model/_shared.py +++ b/packages/zarr-metadata/src/zarr_metadata/model/_shared.py @@ -12,10 +12,9 @@ ValidationProblem, is_array, is_object, + non_string_key, outside_of, refine_json, - refine_user_data, - shown_key, with_input, within, ) @@ -54,9 +53,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) @@ -81,24 +78,17 @@ 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 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 - 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 @@ -282,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 @@ -300,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/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/testing/_document.py b/packages/zarr-metadata/src/zarr_metadata/testing/_document.py index 16098f2a97..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: JSON has no others.""" +"""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 b98d392927..ccaeab6024 100644 --- a/packages/zarr-metadata/src/zarr_metadata/typed_json.py +++ b/packages/zarr-metadata/src/zarr_metadata/typed_json.py @@ -74,10 +74,9 @@ 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`, -`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 @@ -91,7 +90,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 +99,5 @@ __all__ = [ "JSONValue", "Loc", - "UserJSONValue", "check", ] diff --git a/packages/zarr-metadata/src/zarr_metadata/v2/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v2/_definition.py index ebe6fc1b04..4eb637b0ec 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, @@ -209,7 +210,16 @@ def _named_configuration( return None, None, () @classmethod - def _envelope_problems(cls, value: object) -> Problems: + 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, loc: Loc = ()) -> Problems: if isinstance(value, str): bad = typestr_problem(value, ()) return () if bad is None else (bad,) @@ -286,7 +296,15 @@ def _named_configuration( ) @classmethod - def _envelope_problems(cls, value: object) -> Problems: + 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, loc: Loc = ()) -> Problems: if not is_object(value): return ( ValidationProblem( 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..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 @@ -2,12 +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._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 ( @@ -51,6 +53,65 @@ 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, as the v2 spec spells it.""" + 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}", + "invalid_value", + ) + + +def _complex_fill_value_rules( + configuration: ZarrV2ScalarConfiguration, nested: Nested, value: ZarrV2ComplexFillValue +) -> Iterator[ValidationProblem]: + """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 _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; 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). + 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: @@ -132,8 +193,10 @@ 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, + fill_value_named=_float_named, ) """`f2`, `f4`, `f8`: IEEE 754 floats. The fill value is a number or a named non-finite value.""" @@ -142,8 +205,10 @@ 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, + 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/_common.py b/packages/zarr-metadata/src/zarr_metadata/v3/_common.py index da8f4f511a..d87233e9ac 100644 --- a/packages/zarr-metadata/src/zarr_metadata/v3/_common.py +++ b/packages/zarr-metadata/src/zarr_metadata/v3/_common.py @@ -37,6 +37,9 @@ def is_zarr_v3_node_type(value: object) -> TypeIs[ZarrV3NodeType]: ZarrV3ExtensionField: TypeAlias = JSONValue """The JSON value of an unknown top-level v3 metadata field. +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. 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/_definition.py b/packages/zarr-metadata/src/zarr_metadata/v3/_definition.py index dc4a3135b1..8bdaa304ca 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 @@ -205,6 +204,14 @@ 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, 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 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 @@ -520,12 +527,6 @@ 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`. 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 @@ -534,19 +535,10 @@ class ExtraFieldDefinition(Definition[C]): definition named after one is refused too. """ - finite: bool = True - """Whether every number in the member must be finite.""" - 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: @@ -580,7 +572,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() @@ -588,10 +580,12 @@ 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: + def _envelope_problems(cls, value: object, loc: Loc = ()) -> Problems: name = cls._named_configuration(value)[0] if name is None: return ( @@ -605,23 +599,36 @@ 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`: 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_json(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_json(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_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 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) @classmethod def _envelope_json(cls, name: str, configuration: Mapping[str, JSONValue]) -> JSONValue: 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 1d13e60f64..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.""" + """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/consolidated.py b/packages/zarr-metadata/src/zarr_metadata/v3/consolidated.py index 4170a8d454..91c2a454a4 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 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..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 @@ -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._sentinel import UNSET from zarr_metadata.definition._definition import Nested -from zarr_metadata.v3._types.data_type import FLOAT_SPECIAL_FILL_VALUES +from zarr_metadata.v3._types.data_type import FLOAT_SPECIAL_FILL_VALUES, FloatSpecialFillValue def float_fill_value_rules( @@ -29,7 +31,10 @@ 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 (`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. @@ -47,7 +52,17 @@ 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): + 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}, " + f"got the number {name}", + "invalid_value", + ) + return + if value in FLOAT_SPECIAL_FILL_VALUES: return try: self.hex_form(value) @@ -60,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.""" @@ -235,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/src/zarr_metadata/v3/data_type/struct.py b/packages/zarr-metadata/src/zarr_metadata/v3/data_type/struct.py index 9034b80443..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 @@ -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,33 @@ 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. 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 + or len(fill_value_problems(field_type, value[name])) == 0 + ): + 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 +185,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/src/zarr_metadata/v3/group.py b/packages/zarr-metadata/src/zarr_metadata/v3/group.py index 99c0431192..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.""" + """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"] diff --git a/packages/zarr-metadata/tests/model/test_array.py b/packages/zarr-metadata/tests/model/test_array.py index 2d2ae6cf27..d08c273782 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"), @@ -1578,7 +1579,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( @@ -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 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")]), @@ -2099,20 +2104,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( @@ -2145,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"), ] @@ -2290,7 +2297,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" + ), ) @@ -2336,7 +2345,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 +2354,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,30 +2711,37 @@ 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" - (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" + 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 + ][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()]): - 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( + 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}}} @@ -2747,10 +2763,17 @@ 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 + 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 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_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 e7c9fecc98..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 @@ -196,15 +195,18 @@ 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 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 db2729a2e4..f7437e4811 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] @@ -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: - """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.""" - 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"), [ @@ -362,16 +353,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_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..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 @@ -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/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_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_repair.py b/packages/zarr-metadata/tests/model/test_repair.py index 18d7639040..b70d24b8e7 100644 --- a/packages/zarr-metadata/tests/model/test_repair.py +++ b/packages/zarr-metadata/tests/model/test_repair.py @@ -3,12 +3,17 @@ from __future__ import annotations import copy +import dataclasses import json import math -from typing import Any +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, @@ -26,6 +31,16 @@ 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, +) + +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"} @@ -292,7 +307,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. @@ -303,6 +318,138 @@ 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.""" + + +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_rules=_refuses_non_finite, + fill_value_named=_pair_named, +) +"""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": { + "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",)]), + # 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", "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_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}) + 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 + + +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_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) + + +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=[]) + 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_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( ("files", "model", "repaired_at"), [ diff --git a/packages/zarr-metadata/tests/model/test_store_json.py b/packages/zarr-metadata/tests/model/test_store_json.py index 5a8d135e41..4d65528ec1 100644 --- a/packages/zarr-metadata/tests/model/test_store_json.py +++ b/packages/zarr-metadata/tests/model/test_store_json.py @@ -236,29 +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. @@ -292,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}, }, }, ), @@ -302,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] == [ @@ -321,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 new file mode 100644 index 0000000000..581945c887 --- /dev/null +++ b/packages/zarr-metadata/tests/model/test_typed_document.py @@ -0,0 +1,355 @@ +"""Typing a v3 node document by its TypedDict before a scope reads it: `typed_document`.""" + +from __future__ import annotations + +import json +import math +from typing import TYPE_CHECKING + +import pytest +from typing_extensions import TypedDict + +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 ( + 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, + ArrayExtraFieldDefinition, + CodecDefinition, + DataTypeDefinition, + 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: JSONValue + must_understand: bool + + +class _Mix(TypedDict, closed=True): + codec: ZarrV3CodecDeclaration + scale: float + note: JSONValue + must_understand: bool + + +_NOTE_CONTEXT = CORE_CONTEXT.union( + ZarrV3Context( + array_extra_fields=[ + ArrayExtraFieldDefinition(name="acme.note", configuration=_Note), + ArrayExtraFieldDefinition(name="acme.mix", configuration=_Mix), + ] + ) +) + + +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} + + +@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": b"little"}}, + {"name": "zstd", "configuration": {"level": _PAST_THE_LEVELS}}, + ] + ), + CORE_CONTEXT, + { + (("codecs", 0, "configuration", "endian"), "invalid_type"), + (("codecs", 1, "configuration", "level", ...), "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", "level", ...), "invalid_value"), + }, + ), + # A claimed extension field is refined by the definition that claims + # 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}} + ), + _NOTE_CONTEXT, + {(("acme.note", "note", 1, 0, ...), "invalid_value")}, + ), + ( + _array(**{"acme.note": {"note": [float("nan")], "must_understand": True}}), + _NOTE_CONTEXT, + set(), + ), + # 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, + set(), + ), + ( + _array( + **{ + "acme.mix": _mix( + {"name": "bytes", "configuration": {"endian": b"little"}}, math.inf + ) + } + ), + _NOTE_CONTEXT, + {(("acme.mix", "codec", "configuration", "endian"), "invalid_type")}, + ), + # A key the configuration does not declare is reported, and what it + # holds is still refined. + ( + _array(**{"acme.note": {"note": 1, "must_understand": True, "x": b"x"}}), + _NOTE_CONTEXT, + {(("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. + ( + _array(**{"acme.note": {"note": 1, "must_understand": True, 5: 1}}), + _NOTE_CONTEXT, + {(("acme.note",), "invalid_type")}, + ), + ], + ids=[ + "non-json-codec", + "bytes-and-deep-codecs", + "bad-level-and-deep", + "claimed-deep", + "claimed-nan", + "a-nested-declaration", + "not-json-in-a-nested-declaration", + "not-json-under-unknown-key", + "non-string-key-in-a-member", + ], +) +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) <= 5 else (*problem.loc[:4], ...), problem.kind) + for problem in reading.problems + } + assert found == expected + # 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) + configuration, problems = definition.read_configuration( + _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_type") + ] + + +@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: + # 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) + + +@pytest.mark.parametrize( + ("extra", "expected"), + [ + ({"foo": math.nan}, [(("foo",), "unknown_key")]), + ( + {"foo": b"a", "bar": {1}}, + [ + (("foo",), "unknown_key"), + (("foo",), "invalid_type"), + (("bar",), "unknown_key"), + (("bar",), "invalid_type"), + ], + ), + ({"foo": _deep(JSON_DEPTH - 2)}, [(("foo",), "unknown_key")]), + ({"kind": math.inf}, [(("kind",), "invalid_type")]), + # 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=[ + "a-number-that-is-not-finite", + "two-keys", + "deepest", + "kind-a-number", + "not-json-beside-a-wrong-value", + "non-string-key", + "past-the-levels", + ], +) +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. 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 = { + "zarr_format": 3, + "node_type": "group", + "attributes": {}, + "consolidated_metadata": envelope, + } + alone = read_consolidated_metadata_v3(envelope).problems + in_group = read_group_metadata_v3(group).problems + 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 + ] + + +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 + + +@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": 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_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 7684d07287..cb33581916 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,7 @@ import zarr_metadata.definition import zarr_metadata.v2 import zarr_metadata.v3 +from zarr_metadata._json import JSON_DEPTH from zarr_metadata._typed_json import ( Parsed, Parser, @@ -87,6 +90,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 +183,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 +210,61 @@ 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",)}), + (JSONValue, [math.inf], (math.inf,)), + (Mapping[str, JSONValue], {"a": math.nan}, {"a": math.nan}), + (float, -math.inf, -math.inf), + ], + ids=[ + "str-enum", + "int-enum", + "literal-of-a-str-enum", + "literal-of-an-int-enum", + "sequence", + "fixed-tuple", + "union", + "mapping-proxy", + "json", + "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. 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. + assert json.dumps(typed) == json.dumps(parsed) + assert type(typed) is type(parsed) + + +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"), [ @@ -218,7 +280,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"}}, @@ -272,7 +334,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,)}, []), @@ -1831,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": [{3: 1}]}, ("note", 0), "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", @@ -1848,12 +1906,35 @@ 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)] +@pytest.mark.parametrize( + ("junk", "kind"), + [ + (object(), "invalid_type"), + (b"x", "invalid_type"), + ({1: 2}, "invalid_type"), + ], + 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. + 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",), kind), + ] + + 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. diff --git a/packages/zarr-metadata/tests/v2/test_data_types.py b/packages/zarr-metadata/tests/v2/test_data_types.py index 8561553f63..5f018673c2 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 @@ -16,6 +17,7 @@ canonical_of, default_fill_value, fill_value_problems, + named_fill_value, resolve, ) from zarr_metadata.definition._definition import declarations_of @@ -250,6 +252,10 @@ def test_every_family_has_a_default_fill_value_it_takes(dtype: object, default: (" 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: 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_level_gzip_does_not_read(level: object) -> None: + # Its name still identifies the definition that claims it, which + # 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": 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: @@ -935,6 +949,52 @@ def test_error_a_nested_envelope_s_problem_is_its_own_and_the_rules_are_asked() ] +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. 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 _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 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_type"), + ] + + +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 @@ -1577,13 +1637,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"), ] @@ -1603,7 +1663,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'") ] diff --git a/packages/zarr-metadata/tests/v3/test_fill_values.py b/packages/zarr-metadata/tests/v3/test_fill_values.py index 80ff3e2621..11ae038b90 100644 --- a/packages/zarr-metadata/tests/v3/test_fill_values.py +++ b/packages/zarr-metadata/tests/v3/test_fill_values.py @@ -31,6 +31,7 @@ canonical_fill_value, default_fill_value, fill_value_problems, + named_fill_value, resolve, ) from zarr_metadata.model import ( @@ -167,9 +168,29 @@ 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. - 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( @@ -483,6 +504,71 @@ def not_json(configuration: EmptyConfiguration, nested: Nested, value: object) - canonical_fill_value(resolved, {"x": 1}) +@pytest.mark.parametrize( + ("data_type", "value", "named"), + [ + ("float16", math.nan, "NaN"), + ("float32", math.inf, "Infinity"), + ("float64", -math.inf, "-Infinity"), + ("complex64", [math.nan, 1.5], ("NaN", 1.5)), + ("complex128", ["0x7ff8000000000000", -math.inf], ("0x7ff8000000000000", "-Infinity")), + # Nothing to write by name: a finite number, a name, a hex string. + ("float32", 1.5, UNSET), + ("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), + # A fill value that is not JSON, or not of the type's shape. + ("float32", b"x", UNSET), + ("float32", [math.nan], UNSET), + ], +) +def test_a_fill_value_s_named_spelling_writes_each_number_its_type_names( + data_type: JSONValue, value: object, named: object +) -> 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"), [ 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") ]