Skip to content

Commit c0d4b3c

Browse files
d-v-bclaude
andcommitted
fix(array): store upgraded metadata before writing the first chunk
An array read from a stored document that the upgrades had to correct (a chunk size of 0, `false` or `true`) wrote chunks under the corrected layout while the store kept the old document, so zarr 3.2.1-3.4.0 then read only the fill value, and tensorstore and zarrs could not open it. `from_dict` now marks the metadata it read from an upgraded document (`_stored_document_upgraded`, a field outside the document and equality), and `AsyncArray._set_selection`, which every chunk write goes through (`setitem` now included), stores that metadata first and keeps the stored copy. Concurrent first writes store the same document. The array lifecycle state machine now ends the legacy state on a write and checks that no chunk is stored under a document that is still upgraded on read; `resave_metadata` runs only while the stored document is invalid, and re-saving valid metadata is checked once, at creation. The changelog also says which releases stored a chunk size of 0 on an axis of positive length. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 2e878cf commit c0d4b3c

7 files changed

Lines changed: 113 additions & 18 deletions

File tree

‎changes/4334.bugfix.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@ A chunk edge length is now always at least 1, while an array extent may be 0. Ev
22

33
Metadata built in code is strict about chunk edge lengths: `ArrayV2Metadata`, `RegularChunkGridMetadata`, `RectilinearChunkGridMetadata` and `ShardingCodec` take them as Python `int`s of at least 1, so a size of 0 now raises a `ValueError`, and a `bool`, a float or a NumPy integer (including a scalar `chunks=np.int64(5)` for `ArrayV2Metadata`) raises a `TypeError`; `FixedDimension(size=0, ...)` raises a `ValueError`. Stored rectilinear chunk grids with integral floats (`10.0`) are rejected too. The array creation functions still accept NumPy integers in `chunks=` and `shards=`.
44

5-
Stored metadata with a regular chunk size of 0 or JSON `false`, as zarr-python wrote for arrays created with a zero-length axis until 3.4, now opens with a `ZarrUserWarning` and is read as one chunk spanning the axis (a multiple of the inner chunk size for sharded arrays, which previously failed to open). JSON `true`, as zarr-python 3.0 and 3.2 wrote for `chunks=(True,)`, is read as 1, in the chunk grid and in the inner chunk shape of a sharding codec. The warning names the array and says how to store valid metadata: `array.update_attributes({})`, then `zarr.consolidate_metadata` if the metadata is consolidated.
5+
Stored metadata with a regular chunk size of 0 or JSON `false` now opens with a `ZarrUserWarning` and is read as one chunk spanning the axis (a multiple of the inner chunk size for sharded arrays, which previously failed to open). zarr-python wrote such sizes for arrays created with a zero-length axis until 3.4, and, from 2.18.7 to 3.2.1, for an explicit chunk size of 0 or `False` on an axis of any length, as in `chunks=(0,)` (those arrays could store no data). JSON `true`, as zarr-python 3.0 and 3.2 wrote for `chunks=(True,)`, is read as 1, in the chunk grid and in the inner chunk shape of a sharding codec. The warning names the array and says how to store valid metadata: `array.update_attributes({})`, then `zarr.consolidate_metadata` if the metadata is consolidated. Writing data to such an array first stores the upgraded metadata, so that other readers find the chunks written.

‎src/zarr/abc/metadata.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,13 @@ def to_dict(self) -> dict[str, JSON]:
2020
Recursively serialize this model to a dictionary.
2121
This method inspects the fields of self and calls `x.to_dict()` for any fields that
2222
are instances of `Metadata`. Sequences of `Metadata` are similarly recursed into, and
23-
the output of that recursion is collected in a list.
23+
the output of that recursion is collected in a list. Fields declared with
24+
`compare=False` are not part of the document.
2425
"""
2526
out_dict = {}
2627
for field in fields(self):
28+
if not field.compare:
29+
continue
2730
key = field.name
2831
value = getattr(self, key)
2932
if isinstance(value, Metadata):

‎src/zarr/core/array.py‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1623,6 +1623,12 @@ async def _set_selection(
16231623
prototype: BufferPrototype,
16241624
fields: Fields | None = None,
16251625
) -> None:
1626+
if self.metadata._stored_document_upgraded:
1627+
# Chunks are about to be stored under the upgraded metadata, so store it
1628+
# first: every reader of the store then agrees with them.
1629+
metadata = replace(self.metadata)
1630+
await self._save_metadata(metadata)
1631+
object.__setattr__(self, "metadata", metadata)
16261632
return await _set_selection(
16271633
self.store_path,
16281634
self.metadata,
@@ -1674,16 +1680,10 @@ async def setitem(
16741680
- This method is asynchronous and should be awaited.
16751681
- Supports basic indexing, where the selection is contiguous and does not involve advanced indexing.
16761682
"""
1677-
return await _setitem(
1678-
self.store_path,
1679-
self.metadata,
1680-
self.codec_pipeline,
1681-
self.config,
1682-
self._chunk_grid,
1683-
selection,
1684-
value,
1685-
prototype=prototype,
1686-
)
1683+
if prototype is None:
1684+
prototype = default_buffer_prototype()
1685+
indexer = BasicIndexer(selection, shape=self.metadata.shape, chunk_grid=self._chunk_grid)
1686+
return await self._set_selection(indexer, value, prototype=prototype)
16871687

16881688
@property
16891689
def oindex(self) -> AsyncOIndex[T_ArrayMetadata]:

‎src/zarr/core/metadata/v2.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,9 @@ class ArrayV2Metadata(Metadata):
7272
compressor: Numcodec | None
7373
attributes: dict[str, JSON] = field(default_factory=dict)
7474
zarr_format: Literal[2] = field(init=False, default=2)
75+
_stored_document_upgraded: bool = field(default=False, init=False, compare=False, repr=False)
76+
"""Whether `from_dict` read this metadata from a stored document it had to upgrade,
77+
so the store holds an invalid document until this metadata is stored."""
7578

7679
def __init__(
7780
self,
@@ -184,7 +187,7 @@ def from_dict(cls, data: dict[str, Any], *, path: str | None = None) -> ArrayV2M
184187
# zarr v2 allowed arbitrary keys here.
185188
# We don't want the ArrayV2Metadata constructor to fail just because someone put an
186189
# extra key in the metadata.
187-
expected = {x.name for x in fields(cls)}
190+
expected = {x.name for x in fields(cls) if x.init}
188191
expected |= {"dtype", "chunks"}
189192

190193
# check if `filters` is an empty sequence; if so use None instead and raise a warning
@@ -206,6 +209,7 @@ def from_dict(cls, data: dict[str, Any], *, path: str | None = None) -> ArrayV2M
206209

207210
metadata = cls(**_data)
208211
warn_readings(readings, path)
212+
object.__setattr__(metadata, "_stored_document_upgraded", bool(readings))
209213
return metadata
210214

211215
def to_dict(self) -> dict[str, JSON]:

‎src/zarr/core/metadata/v3.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,9 @@ class ArrayV3Metadata(Metadata):
478478
node_type: Literal["array"] = field(default="array", init=False)
479479
storage_transformers: tuple[dict[str, JSON], ...]
480480
extra_fields: dict[str, AllowedExtraField]
481+
_stored_document_upgraded: bool = field(default=False, init=False, compare=False, repr=False)
482+
"""Whether `from_dict` read this metadata from a stored document it had to upgrade,
483+
so the store holds an invalid document until this metadata is stored."""
481484

482485
def __init__(
483486
self,
@@ -678,6 +681,7 @@ def from_dict(cls, data: dict[str, JSON], *, path: str | None = None) -> Self:
678681
storage_transformers=_data_typed.get("storage_transformers", ()), # type: ignore[arg-type]
679682
)
680683
warn_readings(readings, path)
684+
object.__setattr__(metadata, "_stored_document_upgraded", bool(readings))
681685
return metadata
682686

683687
def to_dict(self) -> dict[str, JSON]:

‎tests/test_array_stateful.py‎

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
RuleBasedStateMachine,
3131
initialize,
3232
invariant,
33+
precondition,
3334
rule,
3435
)
3536

@@ -46,6 +47,7 @@
4647
]
4748

4849
DTYPE = np.dtype("int16")
50+
METADATA_KEYS = (".zarray", ".zattrs", "zarr.json")
4951
MAX_SIDE = 6
5052

5153

@@ -67,6 +69,10 @@ def _rectilinear_dim(extent: int) -> st.SearchStrategy[int | list[int]]:
6769
return steps | edges
6870

6971

72+
async def _list(store: MemoryStore, prefix: str) -> list[str]:
73+
return [key async for key in store.list_prefix(prefix)]
74+
75+
7076
class ArrayLifecycle(RuleBasedStateMachine):
7177
def __init__(self) -> None:
7278
super().__init__()
@@ -136,6 +142,11 @@ def create(self, data: st.DataObject) -> None:
136142
stored_zero = data.draw(st.sampled_from([0, False]), label="stored zero")
137143
self._rewrite_stored_chunks(zarr_format, self.legacy_axes, stored_zero)
138144
event("legacy zero chunk size")
145+
else:
146+
# Re-saving valid metadata, as the warning tells users to, changes nothing.
147+
arr = self._open()
148+
arr.update_attributes({})
149+
assert self._open().metadata == arr.metadata
139150

140151
def _rewrite_stored_chunks(
141152
self, zarr_format: Literal[2, 3], axes: list[int], value: Any
@@ -233,9 +244,11 @@ def append(self, data: st.DataObject) -> None:
233244
@rule(data=st.data())
234245
def resize(self, data: st.DataObject) -> None:
235246
arr = self._open()
236-
new_shape = data.draw(
237-
st.tuples(*(st.integers(0, MAX_SIDE) for _ in self.shape)), label="new shape"
238-
)
247+
extents = [st.integers(0, MAX_SIDE) for _ in self.shape]
248+
for axis in self.legacy_axes:
249+
# What a user of an older release did next: grow an axis stored with chunk size 0.
250+
extents[axis] = st.integers(self.shape[axis] + 1, MAX_SIDE + 1) | extents[axis]
251+
new_shape = data.draw(st.tuples(*extents), label="new shape")
239252
note(f"resize {self.shape} -> {new_shape}")
240253
if any(new_shape[axis] > self.shape[axis] for axis in self.legacy_axes):
241254
event("grow an axis stored with chunk size 0")
@@ -256,11 +269,14 @@ def write(self, data: st.DataObject) -> None:
256269
note(f"write {region}")
257270
arr[region] = values
258271
self._model_write(arr, region, values)
272+
# Writing chunks first stores the metadata they are written under.
273+
self.legacy_axes = []
259274

275+
@precondition(lambda self: self.legacy_axes)
260276
@rule()
261277
def resave_metadata(self) -> None:
262-
"""What the warning for an invalid stored chunk size tells users to do. It stores
263-
the metadata as read, which is a no-op for valid metadata."""
278+
"""What the warning for an invalid stored chunk size tells users to do: store
279+
the metadata as read."""
264280
arr = self._open()
265281
read = arr.metadata
266282
arr.update_attributes({})
@@ -271,6 +287,14 @@ def teardown(self) -> None:
271287
self._rectilinear.__exit__(None, None, None)
272288

273289
# ------------------------------------------------------------ invariants
290+
@invariant()
291+
def no_chunk_under_an_invalid_document(self) -> None:
292+
"""While the stored document is still one that is upgraded on read, which other
293+
readers may reject or read differently, no chunk is stored under it."""
294+
if self.legacy_axes:
295+
keys = sync(_list(self.store, f"{self.path}/"))
296+
assert set(keys) <= {f"{self.path}/{name}" for name in METADATA_KEYS}, keys
297+
274298
@invariant()
275299
def matches_model(self) -> None:
276300
arr = self._open()

‎tests/test_metadata/test_upgrades.py‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import asyncio
56
import json
67
import re
78
import warnings
@@ -20,6 +21,7 @@
2021
upgrade_array_document,
2122
)
2223
from zarr.core.metadata.v3 import RectilinearChunkGridMetadata, RegularChunkGridMetadata
24+
from zarr.core.sync import sync
2325
from zarr.dtype import Int16
2426
from zarr.errors import ZarrUserWarning
2527

@@ -345,6 +347,64 @@ def store_legacy(doc: dict[str, Any]) -> None:
345347
np.testing.assert_array_equal(reopened[...], np.concatenate([data, block]))
346348

347349

350+
@pytest.mark.parametrize(
351+
("zarr_format", "shape", "inner", "expected"),
352+
[(2, (3,), None, (3,)), (3, (3,), None, (3,)), (3, (10,), (4,), (12,))],
353+
ids=["v2", "v3", "v3-sharded"],
354+
)
355+
@pytest.mark.parametrize("api", ["sync", "async", "async-concurrent"])
356+
def test_write_stores_upgraded_metadata_first(
357+
tmp_path: Path,
358+
zarr_format: Literal[2, 3],
359+
shape: tuple[int, ...],
360+
inner: tuple[int, ...] | None,
361+
expected: tuple[int, ...],
362+
api: str,
363+
) -> None:
364+
"""Writing chunks to an array read from an upgraded document first stores the
365+
upgraded metadata, so readers that do not upgrade (or read it differently) see
366+
the chunks the write stored."""
367+
path = tmp_path / "legacy.zarr"
368+
zarr.create_array(
369+
store=path,
370+
shape=shape,
371+
chunks=inner or expected,
372+
shards=expected if inner else None,
373+
dtype="int16",
374+
fill_value=0,
375+
zarr_format=zarr_format,
376+
)
377+
_rewrite_doc(
378+
path,
379+
zarr_format,
380+
lambda doc: (
381+
doc.update(chunks=[0])
382+
if zarr_format == 2
383+
else doc["chunk_grid"]["configuration"].update(chunk_shape=[0])
384+
),
385+
)
386+
data = np.arange(1, shape[0] + 1, dtype="int16")
387+
with pytest.warns(ZarrUserWarning, match="is read as"):
388+
arr = zarr.open_array(store=path, mode="r+")
389+
if api == "sync":
390+
arr[:] = data
391+
elif api == "async":
392+
sync(arr.async_array.setitem(slice(None), data))
393+
else:
394+
395+
async def write_twice() -> None:
396+
# Both writes find the metadata not yet stored, and both store it.
397+
await asyncio.gather(*(arr.async_array.setitem(slice(None), data) for _ in "ab"))
398+
399+
sync(write_twice())
400+
401+
with warnings.catch_warnings():
402+
warnings.simplefilter("error", ZarrUserWarning)
403+
reopened = zarr.open_array(store=path, mode="r")
404+
assert (reopened.shards or reopened.chunks) == expected
405+
np.testing.assert_array_equal(reopened[...], data)
406+
407+
348408
@pytest.mark.filterwarnings("ignore:Consolidated metadata is currently not part:UserWarning")
349409
@pytest.mark.parametrize("zarr_format", [2, 3])
350410
def test_legacy_chunk_size_consolidated(tmp_path: Path, zarr_format: Literal[2, 3]) -> None:

0 commit comments

Comments
 (0)