Skip to content

feat(zarr-metadata): return each model with its document in its simplest equivalent spelling - #4642

Merged
d-v-b merged 14 commits into
zarr-developers:mainfrom
d-v-b:feat/zarr-metadata-canonical-documents
Dec 4, 2026
Merged

d-v-b merged 14 commits into
zarr-developers:mainfrom
d-v-b:feat/zarr-metadata-canonical-documents

Conversation

@d-v-b

@d-v-b d-v-b commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🤖 AI text below 🤖

Each model has a canonicalize method that returns the model with its document in its simplest equivalent spelling: ZarrV3ArrayMetadata, ZarrV3GroupMetadata, ZarrV3ConsolidatedMetadata, ZarrV2ArrayMetadata, ZarrV2GroupMetadata and ZarrV2ConsolidatedMetadata. The result equals the model. Every model equal to it, in the same scope, gives the same document, apart from the order of the members of an object, so to_key_value with JSONWriter(sort_keys=True) writes the same bytes for equal models. The document is written from the parts == compares: each declaration as canonical_of writes it, each v3 codec as codec_for_chunk returns it for the chunk it receives, and the fill value as canonical_fill_value writes it. Empty attributes, empty v3 storage_transformers and a v2 dimension_separator of "." are left out, and everything else is kept as written. A v3 group keeps the documents its consolidated metadata lists as written, because a group compares them as written: consolidated().canonicalize() gives them in their simplest spelling, but a group with that listing written back does not equal the original.

Why

The models already say when two documents mean the same thing, but to_json writes each as given, so "equal models may still write different documents". A consumer that needs one spelling had to rebuild it. pydantic-zarr does, in ArraySpec.canonicalize_codecs and canonicalize_fill_value, so that specs compare equal field by field, and its copy of the codec rules drifted from this package's (fixed in zarr-developers/pydantic-zarr#203). With this method it can ask for ZarrV3ArrayMetadata.from_json(document).canonicalize().to_json(). A canonical document also gives a content key for metadata, which nothing provided.

Design notes
  • A model, not a flag on to_json. canonicalize returns a model, so to_json, to_key_value and every typed view work on the result, and the canonical document is read again, which checks it as every document is checked.
  • Written from what == compares. Each model's canonical document is assembled from the same parts as its key (array_key_of for the v3 array), but in a walk written separately from the key's. Property tests check, for v3 and for v2 documents, that the two agree about which spellings are one. fix(zarr-metadata): derive each model's key, canonicalize and refines from one normal form #4648 replaces the separate walks with one normal form per model.
  • Member order is left to the writer. JSON gives the order of an object's members no meaning, and the models compare uninterpreted JSON as sorted text. The canonical document keeps the members that remain in the order they were written, and JSONWriter(sort_keys=True) gives the byte-level normal form.
  • What is left out. Only members whose absence means the same to ==: empty attributes, empty storage_transformers, a v2 dimension_separator of ".". dimension_names of nulls and v2 filters: [] are kept, because == tells them from an absent or null member.
  • Groups and consolidated metadata. A group does not read the documents its consolidated_metadata lists, and compares them as written, so its canonicalize keeps them as written. ZarrV3ConsolidatedMetadata.canonicalize canonicalizes each node it lists. A listed group is written as its own canonicalize writes it, so that group's own listing is kept as written too: simplifying it would give a model that does not equal the original. For the same reason, writing a canonical listing back with group.replace(consolidated_metadata=...) gives a group that does not equal the original. ZarrV2ConsolidatedMetadata.canonicalize rewrites each node's .zarray or .zgroup entry, drops an empty .zattrs entry of a node, and keeps every other entry.
  • v2 codecs grow. The v2 definitions' canonical writes each numcodecs default a codec leaves out, so a canonical v2 document can be longer than its source. That is existing behaviour of canonical_of, and the guide says so.
  • Unclaimed names. The configuration of a declaration nothing in scope claims is kept as written. Its envelope is written in the shortest form, without an empty configuration or a must_understand of true, which is how == already compares it. A bytes codec after one keeps its endian, since the chunk it receives is unknown.
  • The Hypothesis strategies' spellings="canonical" still means each declaration in the spelling canonicalize gives it. A document drawn that way is not always a fixed point of the model's canonicalize (it can hold empty attributes, or an endian on single-byte values).
Tests and checks
  • tests/model/test_canonicalize.py:
    • one parametrized test of document to canonical document across the six models, read in scopes that are not the default ones, which also checks the class, the scope, equality, the hash and that a second canonicalize changes nothing;
    • one test that equal models give one document, and that a sorting writer writes the same bytes;
    • one test that unequal models keep different documents;
    • Hypothesis tests over array_documents (both spellings), group_documents and consolidated_group_documents: every drawn model equals its canonical model, which keeps the scope, is a fixed point, holds no empty attributes or storage_transformers, survives a round trip through JSON text, and is the canonical model of the same document with every object reordered;
    • one Hypothesis test that an array document, and the same document with each declaration in its own simplest spelling, are one array with one canonical document;
    • one Hypothesis test over v2 array documents and a respelled twin of each (one-byte dtype byte order, a dimension_separator of "." and empty attributes written or left out, zstd with and without checksum, an integer or float fill value, 1e39 and "Infinity" for <f4): a document and its twin give one canonical document, two documents are equal exactly when their canonical documents are, and each canonical document leaves out the members whose absence means the same. The property tests run without Hypothesis's deadline.
  • The table test also covers a v3 listing that holds a group with its own listing.
  • docs/models.md gains a "Canonical documents" section, whose examples run in the docs tests.
  • Run locally: the package suite on Python 3.11 and 3.14 (just test-versions), ruff 0.17.3, pyright, mkdocs build --strict, the changelog check and the pre-commit hooks.
Review record

A second review by a fresh subagent, given the diff and the contract but not earlier conclusions, ran on 2026-11-30 against this branch with main merged in. It found no contract failure with the built-in definitions, including 3,000 Hypothesis examples per document strategy. The agent reproduced each finding before acting on it.

  1. Nested listings. The ZarrV3ConsolidatedMetadata.canonicalize docstring promised every listed document in its simplest spelling, but a listed group keeps its own listing as written. Recursing would break the first promise, that the result equals the model, because a group compares its listing as written; a probe confirmed this. Fixed as documentation and a test in 4358daa.
  2. v2 codec defaults and older numcodecs. A canonical v2 document writes numcodecs defaults such as "location" on crc32 and "checksum": false on zstd. numcodecs 0.12.1 rejects both, 0.13.1 rejects the crc32 one, and 0.14 accepts both. So a canonical .zarray written to a store can fail to open there where the original opens. Closed with no change: zarr-python requires numcodecs>=0.16.6, which accepts every default the canonical form writes, and the v2 definitions describe numcodecs 0.16. Leaving the defaults out instead would let one document mean different things to different readers, because numcodecs changes its defaults: zstd's default level is 1 in 0.12.1 and 0 from 0.13.
  3. Unchecked fill_value_canonical. A custom data type whose fill_value_canonical returns a different value gives a result that does not equal the model. One that returns a value of the wrong type raises MetadataValidationError against the document rather than the definition. Open; it is the same class of problem as fix(zarr-metadata): simplify a codec for its chunk in its canonical spelling, and check the result #4647.
  4. Wording. "Simplest equivalent spelling" claims more than == does. An identity transpose and two spellings of one rectilinear grid are kept as written, because == tells them apart. Open.

When the full suite ran locally under heavy machine load, two of the new property tests failed once each and passed on rerun, with no failing example saved. That pointed to Hypothesis's default 200 ms deadline, which the property tests no longer use (see below).

Review on 2026-12-04. A fresh subagent reviewed the open zarr-metadata PRs, and the agent confirmed each finding before acting on it. Each fix was then reviewed by fresh subagents given the diff; rounds 1 and 2 found nothing serious.

Finding Outcome
Hypothesis deadline flakes in the property tests Fixed in bf2366a (deadline=None)
The docs said every unclaimed declaration drops a must_understand of true; an extra field keeps it Fixed in bf2366a (docs and ZarrV3ArrayMetadata.canonicalize docstring)
The canonical_of docstring named canonicalize ambiguously Fixed in bf2366a
No v2 test that the canonical writer and == agree Fixed in bf2366a; round 1 found the 1e39 spelling was never respelled, fixed in 0acef83; round 2 found a pyright error in that commit, fixed in 1b01f1f
A group compares its consolidated listing as written, so writing back consolidated().canonicalize() gives an unequal group Left as designed; the changelog states it (bf2366a, 0acef83). Whether a group should compare listed documents by value is the author's decision
This description said the tests do not reorder configurations that hold declarations, and that the key and the document "cannot disagree" Corrected here: _reordered reverses every object, and the agreement is tested, not structural

Stack bookkeeping

🤖 Generated with Claude Code

…the chunk it receives

A definition's `canonical` reduces two spellings of a configuration to
one when they mean the same thing wherever the declaration is used. It
receives the configuration alone, so it cannot reduce spellings that
mean the same thing only for some chunks. The `endian` of a `bytes`
codec is one: it means nothing when each value takes one byte, and is
required when a value takes several.

`ArrayCodecDefinition` gains `chunk_canonical`, a function of the
configuration, the nested declarations and the chunk, and
`codec_for_chunk` returns the codec of a `Stage` in that spelling, with
each codec of the pipelines it contains simplified for the chunk that
one receives. The result is a declaration, so `declaration_key`,
`canonical_of` and `refines` work on it as on any other. Its
configuration is checked again: the definition must allow it, the chunk
rules must find no problem with it, and each nested declaration must
stay as it is.

`bytes` declares a `chunk_canonical` that drops `endian` for a data type
stored in single bytes, and a v3 array model compares, hashes and
refines by its codecs as `codec_for_chunk` returns them. So an `int8`
array is one array with either `endian` or with none, as zarr-python 3.0
and 3.1 write it, while a `bytes` codec after a `cast_value` to a
multi-byte data type is still compared by its `endian`.

Assisted-by: ClaudeCode:claude-fable-5-2
…est equivalent spelling

Two models are equal when their documents mean the same thing, and
`to_json` writes each document as it was given, so equal models can
write different documents. A consumer that needs one spelling for all of
them, to compare documents field by field or to hash them, had to
normalize each member itself.

Each model gains `canonicalize`: the v3 and v2 array, group and
consolidated metadata models. It returns the model read from its
document in its simplest equivalent spelling, written from the parts
that `==` compares: each declaration as `canonical_of` writes it, each
v3 codec as `codec_for_chunk` returns it for the chunk it receives, and
the fill value in the canonical spelling of its data type. Empty
`attributes`, empty v3 `storage_transformers` and a v2
`dimension_separator` of "." are left out, since a document without them
means the same. Everything else is kept as written.

The result equals the model, and equal models in one scope give the
same document apart from the order of the members of an object, which a
`JSONWriter(sort_keys=True)` sorts. A group keeps the documents its
`consolidated_metadata` lists as written, since it does not read them;
the consolidated metadata models canonicalize each node they list.

Assisted-by: ClaudeCode:claude-fable-5-2
@github-actions github-actions Bot added needs release notes Automatically applied to PRs which haven't added release notes zarr-metadata Specific to the zarr-metadata sub-package labels Nov 16, 2026
@read-the-docs-community

read-the-docs-community Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

📖 7 files modified


Preview · build overview · zarr-metadata · built Dec. 4, 2026, 9:02 p.m. UTC

@codecov

codecov Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.06%. Comparing base (12b4721) to head (db60cc6).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #4642   +/-   ##
=======================================
  Coverage   95.06%   95.06%           
=======================================
  Files          96       96           
  Lines       14126    14126           
=======================================
  Hits        13429    13429           
  Misses        697      697           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…canonical-documents

Main now carries the chunk-aware canonical hook (zarr-developers#4640) and the nested declaration order fix (zarr-developers#4641). The one conflict was in model/_array_v3.py, where this branch adds canonical_array_document_v3 next to codecs_for_chunks; both are kept.

Assisted-by: ClaudeCode:claude-fable-5-2
…at are not the default

A review found that the Hypothesis tests passed with a canonicalize that returned the model's own document, that no test noticed a model losing its scope, and that four behaviours had no case: a claimed extra field, a v2 fill value, a chunk grid and a storage transformer that are respelled.

The parametrized cases are now read in scopes that are not the default ones. The generated documents are compared with the same document reordered at every depth and, for arrays, with each declaration in its own simplest spelling. The reordering helper reverses every object, which the fix in zarr-developers#4641 allows.

Assisted-by: ClaudeCode:claude-fable-5-2
…g claims

Its configuration is kept, but its envelope is written in the shortest form: an empty configuration and a must_understand of true are left out.

Assisted-by: ClaudeCode:claude-fable-5-2
d-v-b and others added 6 commits November 30, 2026 22:33
…written

A group compares the documents its consolidated_metadata lists as
written, so ZarrV3ConsolidatedMetadata.canonicalize writes a listed group
as that group's own canonicalize does and keeps the group's own listing
as written. Simplifying it would give a model that does not equal the
original. The docstrings no longer promise every listed document in its
simplest spelling, and no longer suggest that writing a canonical listing
back with replace(consolidated_metadata=...) gives an equal group.

The table test gains a listing that holds a group with its own listing.

Assisted-by: ClaudeCode:claude-opus-5-5
…ment exactly when equal

Add a property test that draws v2 array documents with a respelled twin
and asserts that canonicalizing is idempotent, round-trips, and agrees
with `==`. Lift the hypothesis deadline on the canonicalize property
tests. Correct the docs on which declarations drop `must_understand`,
the `canonical_of` docstring, and say in the changelog that a group
keeps its consolidated listing as written.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… v2 canonicalize test

The respelled twin now swaps `1e39` and `"Infinity"` for a `<f4` fill
value, and the test checks that the canonical document leaves out a
`dimension_separator` of "." and empty attributes, and keeps the
model's context.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…embers

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@d-v-b
d-v-b marked this pull request as ready for review December 4, 2026 21:33
@d-v-b
d-v-b merged commit 4b40a9c into zarr-developers:main Dec 4, 2026
44 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs release notes Automatically applied to PRs which haven't added release notes zarr-metadata Specific to the zarr-metadata sub-package

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant