Skip to content

fix(metadata)!: make chunk sizes strict in metadata constructors and chunk specifications - #4431

Draft
d-v-b wants to merge 175 commits into
zarr-developers:mainfrom
d-v-b:fix/strict-chunk-sizes
Draft

d-v-b wants to merge 175 commits into
zarr-developers:mainfrom
d-v-b:fix/strict-chunk-sizes

Conversation

@d-v-b

@d-v-b d-v-b commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

🤖 AI text below 🤖

Target: 3.5.0 (minor). Makes chunk sizes strict wherever metadata is built in code and wherever a chunk specification is given to the array creation functions. Stored metadata that a known writer produced keeps opening, through the upgrade module from #4334.

Note

Depends on #4334, #4375, #4376 and #4377 (the 3.4.1 patch PRs), which are merged into this branch, so until they land this diff includes all of them. Review those first; after they merge, this diff shrinks to the tightening below. The changelog fragment is changes/4431.removal.md; it assumes 3.4.1 is released first, since it reverses some of what 3.4.1 says.

Why a separate release

The 3.4.1 PRs fix what was broken without rejecting, changing or newly warning on anything 3.4.0 accepted and handled correctly. That left the metadata constructors lenient: ArrayV2Metadata(chunks=(0,)), True as a chunk size, NumPy integers and scalar chunk shapes are all still accepted there, and each one is a way to build metadata that is invalid or reads back differently. The patch PRs define "one chunk edge length is an int of at least 1" at the metadata boundary; this PR makes the constructors enforce it with no exceptions. Stored documents are still read leniently, but only in zarr.core.metadata.upgrades.

What changes

Strict metadata constructors

ArrayV2Metadata(chunks=...), RegularChunkGridMetadata, RectilinearChunkGridMetadata and ShardingCodec(chunk_shape=...) take chunk edge lengths as Python ints of at least 1, through one rule (parse_chunk_edge) and one chunk-shape type:

Input 3.4.1 This PR
ArrayV2Metadata(chunks=(0,)), ShardingCodec(chunk_shape=(0,)) accepted, written as given ValueError: Dimension 0: chunk edge length must be >= 1, got 0
True / False as a chunk edge length read as 1 / 0 TypeError: Dimension 0: chunk edge length must be an int, got True
NumPy integer (np.int64(5)) accepted in ArrayV2Metadata and ShardingCodec TypeError
scalar chunk shape (chunks=5, chunks=np.int64(5)), or any chunk shape that is not a list or tuple accepted as one dimension TypeError: A chunk shape must be a list or tuple of chunk edge lengths, got 5
float edge (5.0), including run-length encoded sizes and counts TypeError already TypeError

Because the constructors now reject a chunk size of 0, an array built from a metadata object is taken as built: the 3.4.1 path that read a code-built ArrayV2Metadata with a 0 the way a stored 0 is read is removed.

Booleans in chunk specifications: one TypeError

Other than chunks=False or shards=False as the whole specification (one chunk spanning every axis), a boolean anywhere in a specification given to the creation functions raises one TypeError: chunks=True, np.True_, np.False_, a boolean array, chunks=(True, 5), chunks=(False, 5), or a boolean edge in a list. 3.4.1 read these as a chunk size of 1 or 0, or raised a different error for each spelling. chunks=True and create_array(chunks=None) share an automatic-chunking hint:

A bool is not a chunk size; got True. For automatic chunking, pass "auto" to create_array (as chunks= or shards=), or chunks=None to zarr.create.

Legacy Zarr format 2 zarr.create

A falsy chunks no longer means "not given": chunks=0, np.int64(0), chunks=[] and chunks=() raise ValueError, NumPy booleans raise the boolean TypeError, and chunks=False means one chunk spanning the array, as it does for Zarr format 3. chunks=None still chunks automatically.

zarr.testing

chunks_param_from_rectilinear is removed (nothing in zarr used it after arrays() began drawing its chunks= argument from the rectilinear strategies). rectilinear_chunks now returns the full chunks= form, list[int | list[int]]: a dimension may be a bare-int step, which can exceed the extent, so code that treats every dimension as a list (len(dim), sum(dim)) must handle ints. It requires shape to have at least one dimension. The rectilinear strategies are experimental.

What still reads

Every stored document a known writer produced opens as in 3.4.1, because the upgrades run before the strict constructors:

  • a regular chunk size of 0 or false (Zarr format 2 chunks, regular chunk_shape), including sharded arrays;
  • true as a regular chunk size, a rectilinear edge, the size of a run-length pair, or a sharding codec's inner chunk size (nested or not);
  • integral float edges in a rectilinear grid ([[4.0, 2]]);
  • 3.2.x mixed regular grids.

Newly rejected on read, because no known writer stored them and the upgrades do not read them:

  • a scalar stored chunk shape (Zarr format 2 "chunks": 4, a sharding codec's "chunk_shape": 2), which earlier releases read as one dimension, raises a TypeError when the array is opened. A group whose consolidated metadata includes such an array does not open from its consolidated metadata; the error names the member, and use_consolidated=False reaches the other members;
  • true as a rectilinear bare step ("chunk_shapes": [true]) or as a run-length count ([[4, true]]).

Downstream

Code that passes an array's shape as its chunk shape fails for an array with a zero-length axis:

ArrayV2Metadata(chunks=arr.shape, ...)             # ValueError if 0 in arr.shape
RegularChunkGridMetadata(chunk_shape=arr.shape)    # same

Use tuple(max(1, s) for s in arr.shape) instead. VirtualiZarr's kerchunk writer builds ArrayV2Metadata(chunks=np_arr.shape, ...) for inlined arrays, so an empty inlined array would hit this; the project should get a heads-up before 3.5.0. VirtualiZarr's test suite gave identical results on this branch and on the patch branches. The creation functions still accept NumPy integers in chunks= and shards=.

Evidence

  • The 244-row behaviour table (run against a real 3.4.0 install) has a column for this branch: it differs from the patch branches only in the rows summarized above.
  • Stored documents with every reading listed under "What still reads" open on this branch; the stored shapes it newly rejects raise TypeError (tests pin each one).

Tests

One success table for chunk-edge sites (ints only) and one error test per rejection (0, bool, NumPy integer, scalar chunk shape, float) across the three metadata classes and ShardingCodec; one table for the legacy Zarr format 2 chunks argument plus error tests for 0 and []; the boolean TypeError over True and False spellings (except the whole-spec False), including a boolean run-length count; the scalar-chunk consolidated member named in the error.

🤖 Generated with Claude Code

d-v-b and others added 30 commits September 9, 2026 20:28
…, clamps and metadata

Invariant: a chunk edge length is always >= 1; a dimension's extent may be 0,
in which case the dimension has zero chunks (ceildiv(0, size) == 0).

Zero-length-axis bugs have recurred since 2017 (#150, #241, #303, zarr-developers#972,
zarr-developers#1977, zarr-developers#2434, zarr-developers#3711, zarr-developers#4305, zarr-developers#4307, zarr-developers#4328) because the layers disagreed on
this invariant and every span-derived chunk spelling clamped on its own:

- The metadata layer (common.py, metadata/v3.py) required chunk edges >= 1,
  but the in-memory FixedDimension allowed size == 0 with four special-case
  branches left over from zarr-developers#2434, so normalization could build a grid the
  metadata constructor then rejected. FixedDimension now rejects size < 1
  and the four `if self.size == 0` branches are gone. VaryingDimension
  already required edges > 0 and is unchanged.
- `chunks=-1`, `chunks=False`, `chunks="auto"` (_guess_regular_chunks, both
  the typesize == 0 early return and the np.maximum line) and `shards="auto"`
  each derived "one chunk covering the axis" independently. They now all go
  through one helper, `_full_span_chunk_size(span) = max(span, 1)`, which is
  the single definition of that phrase for a possibly zero-length axis.
- Zarr format 2 metadata had no chunk >= 1 check, so a legacy `chunks: [0]`
  document opened fine and read uninitialised memory after a resize. It now
  raises a clear ValueError at parse time, matching the format 3 grid.
- Rectilinear grids had no creation-time spelling for a zero-length axis:
  normalize_chunks_1d required sum(edges) == span, which no list of positive
  edges can satisfy for span 0, even though the same state is reachable via
  resize((0,)) and round-trips through reopen. For span == 0 any non-empty
  list of positive edges is now accepted verbatim, producing the same
  VaryingDimension(edges, extent=0) that resize produces; the strict sum
  check is kept for span > 0.

Tests: the per-spelling regression test from zarr-developers#4328 is replaced by one matrix
over {-1, False, "auto", 1, (1,...), [[2, 2]]} x {(0,), (0, 4), (4, 0),
(0, 0), ()} x {v2, v3} x {no shards, shards="auto" with and without a byte
budget, explicit shards}, with separate small tests for each error case.
Tests that constructed FixedDimension(size=0) now assert it raises, and a
zero-extent test covers the behaviour the old special cases were guarding.

Assisted-by: ClaudeCode:claude-fable-5-1
zarr-python 2.18.7 writes `chunks: [0]` for `zarr.zeros((0,), chunks=False)`
and for `chunks=(0,)`, so stores with that document exist. Rejecting them
at open would turn a previously-readable array into an error; leaving the
0 in place read uninitialised memory after a resize. Normalize the edge to
1 with a ZarrUserWarning instead — the same grid every other "one chunk
spans the axis" spelling produces — and keep rejecting a zero edge on an
axis that has data.

Assisted-by: ClaudeCode:claude-fable-5-1
Assisted-by: ClaudeCode:claude-fable-5-1
Measured against zarr 2.18.7: `zeros((0,), chunks=False)`, `chunks=-1` and
`chunks=(0,)` all write `chunks: [0]`, after which nchunks, read, write,
append, resize and reopen-then-read every raise ZeroDivisionError. There
was never a working behaviour to preserve; normalizing the edge to 1 makes
such arrays usable for the first time. Say so in the comment and fragment
instead of claiming the stores were previously readable.

Assisted-by: ClaudeCode:claude-fable-5-1
zarr 3.2.0 and 3.2.1 classified mixed chunk specs like (2, (5, 10, 5)) as
regular and stored them as a "regular" grid whose chunk_shape contains an
edge list, while laying the chunks out as a rectilinear grid. Newer versions
accepted that metadata and failed later with an unrelated TypeError.

RegularChunkGridMetadata now rejects edge lists. When reading stored
metadata, a "regular" grid with edge lists is read as the rectilinear grid
it describes, with a warning explaining how to re-save it; if rectilinear
chunks are disabled, the error says what happened and how to enable them.

Closes zarr-developers#4374

Assisted-by: ClaudeCode:claude-opus-5
Assisted-by: ClaudeCode:claude-opus-5
…n the 3.2.x shim

Review follow-ups for zarr-developers#4375:

- RegularChunkGridMetadata now accepts numpy integer scalars and stores
  Python ints, mirroring parse_shapelike. The strict integer check had
  reported np.int64(2) as if it were a list of chunk edges.
- The mixed "regular" grid reader converts tuple entries to lists before
  delegating to RectilinearChunkGridMetadata.from_dict, so metadata dicts
  built in Python are handled the same as parsed JSON.
- The error and warning share one message prefix.
- Tests cover numpy ints, run-length encoded edges, and tuple input, and
  the test section header says the reader is broader than the 3.2.x bug.

Assisted-by: ClaudeCode:claude-fable-5-1
The rectilinear hypothesis strategy returned one list of edges per
dimension, so no property test ever saw a bare-int dimension, a grid
mixing bare ints and edge lists, a run-length encoded declaration, or
edges overhanging the extent. The first-element-only classifier that
zarr 3.2.x shipped (zarr-developers#4374) was invisible to it.

The strategies now cover two spaces. `rectilinear_chunks` samples the
`chunks=` syntax: bare ints and flat edge lists in any arrangement, at
least one list so the grid is rectilinear. `rectilinear_chunk_shape_
declarations` samples the stored metadata: bare-int steps (including
larger than the extent), edge lists written in full or run-length
encoded in canonical or arbitrary grouping, and overhanging edges. Each
draw comes with the chunk_shapes it must parse to. `chunk_grids` and so
`array_metadata` draw from the stored space; `arrays` passes grids the
list syntax cannot express as the metadata object, and asserts the
stored grid equals the declared one.

Two property tests pin the properties that would have caught zarr-developers#4374:
every stored declaration parses to its expanded edges and re-serializes
to an equivalent grid, and every `chunks=` specification is stored in
zarr.json as a "rectilinear" grid equal to the specification.

test_unified_chunk_grid.py used a private copy of the old strategy; it
now draws from the shared one.

Assisted-by: ClaudeCode:claude-fable-5-1
Chunk specifications were parsed by `normalize_chunks_nd`, but a separate
duck-typed classifier, `_is_rectilinear_chunks`, ran on the raw input first
at three sites to decide whether the spec was rectilinear. Two opinions on
the same input is the shape of the bug in zarr-developers#4374, and they could disagree:
a 0-d numpy array counted as rectilinear because it has `__iter__`.

The classifier is gone. Each site normalizes first and asks the resulting
`ChunkGrid` (`is_regular`); stored rectilinear metadata passed as
`chunks=` counts as rectilinear even when its edges are uniform. The shard
resolver sends regular and rectilinear shard specs through the same
normalizer.

Also fixed on the way:

- The legacy v2 branch of `AsyncArray.create` tested `chunks or
  chunk_shape`, so `zarr.create(chunks=np.array([...]), zarr_format=2)`
  failed with "truth value of an array is ambiguous". It now uses the
  `is not None` form the v3 branch already had.
- 0-d numpy arrays unwrap to their scalar in both normalizers instead of
  failing with "len() of unsized object".
- A non-integer scalar spec (`2.0`, `np.float64`) raises the normalizer's
  own TypeError instead of "object has no len()".

Assisted-by: ClaudeCode:claude-fable-5-1
Assisted-by: ClaudeCode:claude-fable-5-1
Assisted-by: ClaudeCode:claude-fable-5-1
…k shapes

The chunk_shapes parsers checked exact types: `from_dict` accepted a
dimension only as `int` or `list`, `expand_rle` accepted an RLE pair only
as a `list`, and the reader for 3.2.x mixed grids special-cased `tuple` to
convert it to a list before handing it to `from_dict`. A metadata dict
built in Python holds tuples where parsed JSON holds lists, and a numpy
array is as good as either, so these checks rejected valid input.

One structural predicate, `declares_chunk_edges`, now answers "is this a
sequence of edges rather than a single integer size" for all of them:
any non-integer iterable except `str`/`bytes`. It is a `TypeGuard`, not a
`TypeIs`, because it is False for strings, which are iterable. The four
sites that make that decision use it: `parse_chunk_grid`'s detection of a
mixed grid, the mixed-grid reader, `RectilinearChunkGridMetadata.from_dict`,
and `expand_rle`. The shim no longer needs its tuple special case.

Integers are `int | np.integer` throughout, matching `_parse_chunk_shape`,
and every parser stores Python ints: `_validate_chunk_shapes` now
coerces, so constructing a rectilinear grid from numpy values works the
way it already did for a regular grid.

Assisted-by: ClaudeCode:claude-opus-5
Parsing a regular chunk shape repeated its work at two levels:

- `_parse_chunk_shape` type-checked and coerced every dimension, then
  handed the result to `_validate_chunk_shapes`, which re-ran the same
  isinstance test and coercion and added only the `>= 1` check. Its
  edge-list branch was unreachable from this caller, which is why a
  `cast` was needed on the way out.
- `RegularChunkGridMetadata.from_dict` parsed the chunk shape and passed
  it to the constructor, whose `__post_init__` parsed it again.

Together that was four passes over the dimensions for `from_dict`. It
is now one: `_parse_chunk_shape` checks the range itself and no longer
calls the rectilinear validator, and `from_dict` hands the dimensions to
the constructor unparsed. Beyond the redundancy, the shared validator
was the coupling that let a rectilinear chunk shape be stored as a
regular grid (zarr-developers#4374), so the two grid kinds now validate separately.

`RectilinearChunkGridMetadata.from_dict` also had its own `>= 1` check
for bare-int dimensions, duplicating `_validate_chunk_shapes`, which
`__post_init__` runs over the result anyway. It now only puts the JSON
into shape (integer vs sequence, RLE expansion), and a bad bare int is
reported by the validator, which names the dimension. `expand_rle` keeps
its own checks because it is called directly.

Assisted-by: ClaudeCode:claude-opus-5
… format 3

The compatibility policy for a stored chunk size of 0 on a zero-length
axis covered Zarr format 2 only, so arrays written by zarr-python 3.0 and
3.1 with `chunk_shape: [0]` — or `[false]`, which 3.0 wrote for
`chunks=False` — still could not be opened at all.

`ArrayV3Metadata` now applies the same policy to a regular chunk grid: a
stored chunk size of 0 on a zero-length axis is read as 1 with a
`ZarrUserWarning`, and a zero chunk size on a positive-length axis is
left for the chunk grid parser to reject. It runs in `__init__` rather
than in the grid parser because the policy needs the array shape, which
chunk grid metadata does not carry.

Both warnings now say how to store a corrected chunk size — open the
array writable and call `array.update_attributes({})`, which rewrites the
whole document from the parsed metadata — from one shared constant. The
Zarr format 2 warning also named only zarr-python 2.x; measured against
real installs, every 3.x release before 3.4 wrote a zero chunk size for
an empty array too (3.3.0 for `chunks=-1` and `chunks=False`).

Tested against stores written by zarr 3.0.10, 3.1.6 and 3.3.0: they open,
append without losing data, and re-save to a chunk size that reopens
without a warning.

Assisted-by: ClaudeCode:claude-opus-5
… in one routine

The legacy zero-chunk policy was written out twice: inline in
`ArrayV2Metadata.__init__`, and again in a Zarr format 3 helper. The V2
copy also zipped with `strict=False` and re-appended any trailing chunk
entries only so that a separate length check, `parse_metadata`, could
report a dimensionality mismatch after construction.

`parse_stored_chunk_shape` in `zarr.core.metadata.common` is now the one
place a stored chunk shape is checked against its array's shape, for both
formats: one entry per axis, every integer chunk size at least 1, and a
size of 0 (or JSON `false`) on a zero-length axis read as 1 with a
warning that names the writer and how to re-save. Non-integer entries,
such as edge lists, pass through for the caller's own parser.

`ArrayV2Metadata.__init__` calls it directly and `parse_metadata` is
gone. The Zarr format 3 adapter only locates a regular grid's
`chunk_shape` in the stored document and hands it over; it still runs in
`ArrayV3Metadata.__init__` because chunk grid metadata has no array shape.
The Zarr format 3 import changes that existed only for the old helper are
reverted.

Tests for the policy now target the routine: one table of valid and
legacy inputs, and one test per rejection (dimension mismatch, zero on a
non-empty axis, negative). They replace metadata-level tests in
test_v2.py and test_v3.py that only re-tested the same rules; the
end-to-end tests still cover both formats' wiring against stored arrays.

Assisted-by: ClaudeCode:claude-opus-5
…nk grids

`parse_stored_chunk_shape` passed non-integer entries through "for the
caller's own parser", which made a regular-grid policy look like a
general chunk shape routine and let it decide what a 0-length chunk means
for grids it does not own. A rectilinear grid, or any other grid, is free
to define its own semantics for 0-length chunks.

It is now `parse_stored_regular_chunk_shape`, typed `Sequence[int]`, with
no pass-through, and its docstring says it applies to Zarr format 2
`chunks` and Zarr format 3 `regular` grids only. The Zarr format 3 caller
hands it a chunk shape only when the grid is named `regular` and every
entry is an integer (`_is_regular_chunk_shape`); anything else is not a
regular chunk shape and goes to the chunk grid parser untouched.

Assisted-by: ClaudeCode:claude-opus-5
- Document the `rectilinear_chunks` return type change in the changelog
  fragment, since `zarr.testing.strategies` is public.
- Make the `RectilinearDimDeclaration` alias private.
- Encode canonical RLE in the strategy instead of calling `compress_rle`,
  so the generator does not depend on the code under test.
- Assert `rectilinear_chunks` gets a non-empty shape instead of returning
  a non-rectilinear `[]`.

Assisted-by: ClaudeCode:claude-opus-5-5
# Conflicts:
#	tests/test_properties.py
With zarr-developers#4334 a rectilinear dimension of extent 0 takes any non-empty list of
positive edges at creation, the same state 3.2.x wrote and resize(0)
produces. The strategies asserted extent > 0 and `chunk_grids` fell back to
a regular grid for any empty axis, so no property saw that state.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… into fix/mixed-regular-chunk-grid-4374

# Conflicts:
#	src/zarr/core/metadata/v3.py
…place

zarr-developers#4334 read a zero chunk size on an empty axis in `ArrayV3Metadata.__init__`
and zarr-developers#4375 read a 3.2.x mixed grid inside `parse_chunk_grid`, each with its
own predicate, warning text and re-save advice. Both are compatibility
readings of a stored `regular` grid, so `_read_stored_regular_chunk_grid`
now dispatches to both, `parse_chunk_grid` accepts only what the spec
allows, and both warnings use `RESAVE_METADATA_HINT`.

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

A stored chunk size of 0 was tolerated only on a zero-length axis and
rejected otherwise, because the metadata supposedly could not say how the
stored chunks were laid out. But a chunk size of 0 gives a grid of zero
chunks, so no release could store a chunk under it, and the writers of
that metadata let the axis grow: 3.4.0 appends to a Zarr format 2 array
created empty by 3.3.0 (shape grows, no chunk written), and 3.1.6 records
a Zarr format 3 resize and the resize half of a failed append. Measured
with real installs. Those arrays open in 3.4.0, attributes included; the
rejection would have made them unopenable.

`parse_stored_regular_chunk_shape` now reads a stored 0 (or JSON `false`)
on any axis as one chunk spanning it, `max(extent, 1)`, which is what the
`-1`/`False` spec that wrote it meant. On a grown axis the warning also
says that data written to it was not saved. Negative sizes are still
rejected.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
d-v-b and others added 27 commits September 26, 2026 18:05
Resolution: the refreshed consolidated members are adopted in place, as on
loop/4334, and keep this branch's encode-before-store split. `MemberUpgrade`
and loop/4334's `_Refreshed` become one `RefreshedMember` (holding dict,
name, stale and current member, and the member's documents as read):
`store_node` stores the member upgrades with the group documents, then
adopts every refreshed member. `EncodedNode` drops `metadata` (nothing
adopts a copy any more) and `save_metadata` returns nothing. `_read_array`
re-raises `RectilinearChunksDisabledError`, now raised by
`_check_rectilinear_chunks_enabled` (declared next to it).

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

Storing a group's consolidated metadata reads each upgraded member again
from its own document; one read as a rectilinear chunk grid now raises the
flag error there (naming the array) instead of being kept stale. That
error now also says the group stored nothing, as the encoding error does.
`zarr.consolidate_metadata` without the flag reports the member this way.
The refresh test gains a mixed regular grid row.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`delitem` encodes the group metadata without the member before deleting
it, which reads each upgraded consolidated member again, then stored the
metadata through `save_metadata`, which read them all a second time.

It now adopts the members the first encoding read, after the deletion and
in place, and stores the metadata as it then is with those members'
upgrades (`store_node`), so the first deletion reads each member once.
The handle's consolidated metadata is no longer replaced by writes, so the
deletion pops from it directly.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings the in-place adoption of refreshed consolidated members
(`RefreshedMember.adopt`, `save_metadata` returning None),
`RectilinearChunksDisabledError` re-raised by the member refresh,
the "nothing was stored" note, and `delitem` reusing its validation read.

Resolutions: none needed; the merge applied cleanly. The strict
release's constructors still reach `_check_rectilinear_chunks_enabled`,
which now raises `RectilinearChunksDisabledError` (a `ValueError`), and
`ConsolidatedMetadata.from_dict` keeps its per-member note via
`_member_from_dict`, which preserves the exception type.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Records loop/4377's merge of loop/4334 (dc50ec6, cddb877).
Resolutions: none; the tree is unchanged, since those commits came in
with loop/4375 and 4377's own changes were already merged.

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

Group writes (attributes, `update_attributes`, deleting a member,
`consolidate_metadata`, `create_hierarchy`) read each upgraded member of
the consolidated metadata again from its own document and stored its
upgrade. Those member writes raced concurrent deletions: two concurrent
`delitem`s on a consolidated group recreated a deleted array's metadata
document in most runs, which zarr 3.4.0 never did.

A group write now stores only the group's own documents and reads none.
Array metadata read from a document that had to be upgraded keeps that
document (`_stored_document`, set by `mark_upgraded`, replacing the
`_stored_document_upgraded` flag), and consolidated metadata stores such
a member as it was stored. Every reader of the consolidated metadata then
reads the member as upgraded again, and the array's own first chunk write
stores the upgrade of its current document (or refuses a changed chunk
grid) as before: the only write that upgrades a member document.

Removed: the refresh and adoption of consolidated members in
`save_metadata` (`_refresh_consolidated`, `_refresh_array`,
`_Refreshed`), and `Group.update_attributes_async`'s detour through
`save_metadata`. Tests pinning the refresh are replaced by tests that a
group write reads nothing and writes only the group's documents, stores
the member's consolidated copy byte for byte as stored, that concurrent
deletions leave no member, and that the first write through consolidated
metadata stores the member's upgrade or refuses a changed grid.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Group writes store only the group's own documents (D19). Resolution:

- io.py: `RefreshedMember`, `_read_array`, `_refresh_consolidated`,
  `EncodedNode`, `encode_node` and `store_node` are gone; `save_metadata`
  stores what `encode_documents` encodes.
- `AsyncGroup.delitem` encodes the group without the member (the store
  and the group stay untouched if that fails), deletes the member,
  removes it in place from the shared consolidated metadata, and stores
  the group's documents encoded from its metadata as it then is. It no
  longer reads or stores any member document.
- `GroupMetadata.to_buffer_dict` gates the consolidated members it
  encodes; a member read from a document that had to be upgraded (a
  3.2.x mixed regular grid, say) is stored as it was stored, so it is
  not gated.
- Tests: the mixed-grid group tests now pin that group writes and
  `consolidate_metadata` keep the verbatim document, with or without the
  flag; deleting a member with the flag off is refused when the group
  would store a rectilinear chunk grid.

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

Setting attributes of an array read from a document that had to be
upgraded stored the upgraded document with the new attributes, but left
the metadata marked with the document it was read from. A consolidated
group handle shares that metadata, so its next write stored the old
document in the consolidated metadata and the new attributes were lost
from it (zarr 3.4.0 kept them).

Every write of an array's own documents (creating, resizing, setting
attributes) now goes through `AsyncArray._save_metadata`, which clears
the mark afterwards, as the first chunk write does after storing the
upgrade. Both clear it through `_stored_document_replaced`, the one
place that declares it: the first chunk write clears it also when it
stores nothing (the store already holds a valid document, or none), so
it cannot be folded into the save.

The deep copy in `mark_upgraded` stays: the metadata's attributes share
objects with the document it was read from, which the caller also
holds. A test pins it.

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

Setting attributes on or resizing an array read from a document that needed
an upgrade clears the `_stored_document` mark only after the store accepts the
new metadata. A test now injects a store failure for the array's own document
and checks the mark and the stored bytes survive, for Zarr formats 2 and 3.
The `_save_metadata` docstring now says only what the method does.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 zarr-metadata | 🛠️ Build #34778905 | 📁 Comparing b3e355a against latest (cad2561)

  🔍 Preview build  

3 files changed
± api/model/index.html
± api/pydantic/index.html
± api/v2/index.html

@codecov

codecov Bot commented Sep 26, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.90909% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.52%. Comparing base (d7686f6) to head (b3e355a).
⚠️ Report is 16 commits behind head on main.

Files with missing lines Patch % Lines
src/zarr/core/metadata/upgrades.py 98.13% 3 Missing ⚠️
src/zarr/core/group.py 96.82% 2 Missing ⚠️
src/zarr/core/chunk_grids.py 97.82% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4431      +/-   ##
==========================================
+ Coverage   94.37%   94.52%   +0.15%     
==========================================
  Files          93       94       +1     
  Lines       13171    13497     +326     
==========================================
+ Hits        12430    12758     +328     
+ Misses        741      739       -2     
Files with missing lines Coverage Δ
src/zarr/codecs/sharding.py 95.69% <100.00%> (+0.15%) ⬆️
src/zarr/core/_json.py 100.00% <100.00%> (ø)
src/zarr/core/array.py 98.20% <100.00%> (+0.11%) ⬆️
src/zarr/core/common.py 92.26% <100.00%> (+1.78%) ⬆️
src/zarr/core/metadata/io.py 100.00% <100.00%> (ø)
src/zarr/core/metadata/v2.py 90.65% <100.00%> (+1.27%) ⬆️
src/zarr/core/metadata/v3.py 96.91% <100.00%> (+1.46%) ⬆️
src/zarr/testing/strategies.py 96.99% <100.00%> (+0.36%) ⬆️
src/zarr/core/chunk_grids.py 96.42% <97.82%> (-0.36%) ⬇️
src/zarr/core/group.py 95.34% <96.82%> (+0.12%) ⬆️
... and 1 more

... and 3 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@d-v-b d-v-b added this to the 3.5.0 milestone Sep 27, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant