Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
5f94a6a
refactor(zarr-metadata): type v3 node documents by their TypedDict be…
d-v-b Dec 3, 2026
684fb30
refactor(zarr-metadata): derive the v3 declaration envelope check fro…
d-v-b Dec 3, 2026
3ddee67
fix(zarr-metadata): report every problem the v3 type layer finds, and…
d-v-b Dec 3, 2026
8d76087
refactor(zarr-metadata): refuse at compile time the document members …
d-v-b Dec 4, 2026
9553a2c
test(zarr-metadata): compare nesting-problem locations down to the co…
d-v-b Dec 4, 2026
32b45eb
docs(zarr-metadata): add the changelog entry for typing v3 node docum…
d-v-b Dec 4, 2026
e2eccca
refactor(zarr-metadata): refine values inside the annotation checker …
d-v-b Dec 4, 2026
074377c
fix(zarr-metadata): read declarations in configurations as documents …
d-v-b Dec 4, 2026
da32aeb
fix(zarr-metadata): share the unwritten-configuration rule between bo…
d-v-b Dec 4, 2026
b88c121
fix(zarr-metadata): refine what an unexpected consolidated envelope m…
d-v-b Dec 4, 2026
fcc5795
fix(zarr-metadata): check a consolidated envelope with the checker th…
d-v-b Dec 4, 2026
aec16c1
test(zarr-metadata): pin a non-finite consolidated kind as a value pr…
d-v-b Dec 4, 2026
a14f091
docs(zarr-metadata): describe where a non-finite number may appear in…
d-v-b Dec 4, 2026
1aa86a8
refactor(zarr-metadata)!: make the annotation checker the only judge …
d-v-b Dec 4, 2026
4fb9eed
fix(zarr-metadata): never refuse a declaration that is not JSON witho…
d-v-b Dec 4, 2026
789f2e3
fix(zarr-metadata): run a configuration's rules only on nested declar…
d-v-b Dec 4, 2026
5542559
test(zarr-metadata): pin that a container's rules run beside a nested…
d-v-b Dec 4, 2026
ddacc86
refactor(zarr-metadata)!: leave whether JSON may hold a non-finite nu…
d-v-b Dec 4, 2026
56561b5
refactor(zarr-metadata): drop the purity gate a nested non-finite num…
d-v-b Dec 4, 2026
5d23015
docs(zarr-metadata): describe where a non-finite number may stand now…
d-v-b Dec 4, 2026
c7f34fa
docs(zarr-metadata): say a non-finite number may stand anywhere a num…
d-v-b Dec 4, 2026
a3aa5e7
docs(zarr-metadata): say every value spelled as a float fill value is…
d-v-b Dec 4, 2026
c27d46c
refactor(zarr-metadata): let each data type say which fill value numb…
d-v-b Dec 4, 2026
d4d05fc
fix(zarr-metadata): repair a non-finite number wherever the data type…
d-v-b Dec 4, 2026
d11b6ce
fix(zarr-metadata): run a data type's named spelling only for a fill …
d-v-b Dec 4, 2026
08d0cf7
fix(zarr-metadata): repair only a fill value the data type's rules re…
d-v-b Dec 4, 2026
e9f017a
fix(zarr-metadata): name a struct field only when its own type refuse…
d-v-b Dec 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/zarr-metadata/changes/493.feature.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions packages/zarr-metadata/changes/493.removal.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 3 additions & 1 deletion packages/zarr-metadata/docs/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 13 additions & 4 deletions packages/zarr-metadata/docs/repair.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
31 changes: 17 additions & 14 deletions packages/zarr-metadata/docs/validation-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.**

Expand Down
12 changes: 3 additions & 9 deletions packages/zarr-metadata/src/zarr_metadata/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""


Expand Down
112 changes: 44 additions & 68 deletions packages/zarr-metadata/src/zarr_metadata/_json.py
Original file line number Diff line number Diff line change
@@ -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`.
"""
Expand All @@ -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
Expand Down Expand Up @@ -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, ...]:
Expand All @@ -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)


Expand All @@ -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)
Expand Down Expand Up @@ -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, ...]]
Expand Down Expand Up @@ -464,32 +455,26 @@ 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
elif cls is list or cls is tuple:
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):
Expand Down Expand Up @@ -519,32 +504,23 @@ 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
return (members if len(found_in_members) == 0 else None), tuple(found_in_members)
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 (
Expand Down Expand Up @@ -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.
Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -847,7 +824,6 @@ def arrays_to_tuples(obj: object) -> object:
"parse_json",
"prefixed",
"refine_json",
"refine_user_data",
"refused_kind",
"said",
"shown",
Expand Down
Loading
Loading