Skip to content

Commit f081f1b

Browse files
d-v-bclaude
andcommitted
fix(array): store the upgrade of the current stored document before writing
A handle read from an upgraded document upserts the upgrade of what the store holds on its first non-empty chunk write: a stale handle no longer rolls back newer metadata, and an empty write stores nothing. consolidate_metadata does the same for each upgraded member before writing the consolidated document. Both go through two internal primitives in zarr.core.metadata.io: diff_documents compares a node's stored documents with those its metadata would store, value by value, and upsert_metadata encodes first, then stores only the documents that differ and returns the changes. The upgraded-document flag is a ClassVar set on the instance by one helper, mark_upgraded, which also warns; the upgrades are keyed by Zarr format; the Metadata.to_dict and V2 from_dict changes are reverted. _append goes through AsyncArray.setitem and _setitem is removed. A chunk shape that is not a list or tuple is rejected as a whole, and every expand_rle error names its dimension. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent c1353bf commit f081f1b

13 files changed

Lines changed: 515 additions & 146 deletions

File tree

‎changes/4334.bugfix.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
A chunk edge length is now always at least 1, while an array extent may be 0. Every spelling of one chunk spanning an axis (`chunks=-1`, `chunks=False`, `chunks="auto"`, `shards=-1`, `shards=False`) gives chunk size 1 on a zero-length axis, and a shard spanning an axis is a multiple of the inner chunk size, so `shards=-1` no longer fails when the axis length is not a multiple of it. Rectilinear chunk grids can be created on a zero-length dimension with a non-empty list of positive chunk sizes, which are kept for later growth.
22

3-
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=`.
3+
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`, as does a chunk shape that is not a list or tuple; `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` 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.
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 (other than an empty selection) first stores the upgrade of the metadata the store then holds, unless another writer has stored valid metadata since, so that other readers find the chunks written; `zarr.consolidate_metadata` likewise stores the upgraded metadata of each such array before the consolidated metadata.

‎src/zarr/abc/metadata.py‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,10 @@ 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. Fields declared with
24-
`compare=False` are not part of the document.
23+
the output of that recursion is collected in a list.
2524
"""
2625
out_dict = {}
2726
for field in fields(self):
28-
if not field.compare:
29-
continue
3027
key = field.name
3128
value = getattr(self, key)
3229
if isinstance(value, Metadata):

‎src/zarr/api/asynchronous.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -231,10 +231,15 @@ async def consolidate_metadata(
231231
group = await AsyncGroup.open(store_path, zarr_format=zarr_format, use_consolidated=False)
232232
group.store_path.store._check_writable()
233233

234-
members_metadata = {
235-
k: v.metadata
236-
async for k, v in group.members(max_depth=None, use_consolidated_for_children=False)
234+
members = {
235+
k: v async for k, v in group.members(max_depth=None, use_consolidated_for_children=False)
237236
}
237+
# Store the upgrade of every member document that had to be upgraded before the
238+
# consolidated document that describes the upgraded metadata.
239+
for member in members.values():
240+
if isinstance(member, AsyncArray):
241+
await member._store_upgraded_document()
242+
members_metadata = {k: v.metadata for k, v in members.items()}
238243
# While consolidating, we want to be explicit about when child groups
239244
# are empty by inserting an empty dict for consolidated_metadata.metadata
240245
for k, v in members_metadata.items():

‎src/zarr/codecs/sharding.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,7 @@ class ShardingCodec(
458458
def __init__(
459459
self,
460460
*,
461-
chunk_shape: Iterable[int],
461+
chunk_shape: tuple[int, ...] | list[int],
462462
codecs: Iterable[Codec | dict[str, JSON]] = (BytesCodec(),),
463463
index_codecs: Iterable[Codec | dict[str, JSON]] = (BytesCodec(), Crc32cCodec()),
464464
index_location: ShardingCodecIndexLocation | IndexLocation = "end",

‎src/zarr/core/array.py‎

Lines changed: 23 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,8 @@
118118
ArrayV2MetadataDict,
119119
ArrayV3Metadata,
120120
)
121-
from zarr.core.metadata.io import save_metadata
121+
from zarr.core.metadata.io import save_metadata, upsert_metadata
122+
from zarr.core.metadata.upgrades import upgrade_array_document
122123
from zarr.core.metadata.v2 import (
123124
CompressorLikev2,
124125
get_object_codec_id,
@@ -1615,6 +1616,24 @@ async def _save_metadata(self, metadata: ArrayMetadata, ensure_parents: bool = F
16151616
"""
16161617
await save_metadata(self.store_path, metadata, ensure_parents=ensure_parents)
16171618

1619+
async def _store_upgraded_document(self) -> None:
1620+
"""Store the upgrade of this array's current stored document, if it differs from
1621+
what the store holds.
1622+
1623+
Only for metadata read from a document that had to be upgraded (see
1624+
`zarr.core.metadata.upgrades`). The document is read again, because the store may
1625+
hold a newer one than this handle's metadata: if that one needs no upgrade (the
1626+
array was re-saved or resized since), nothing is stored. Storing the same upgrade
1627+
twice is harmless, so concurrent callers need no coordination.
1628+
"""
1629+
if not self.metadata._stored_document_upgraded:
1630+
return
1631+
zarr_format = self.metadata.zarr_format
1632+
stored = await get_array_metadata(self.store_path, zarr_format=zarr_format)
1633+
upgraded, _ = upgrade_array_document(stored, zarr_format)
1634+
await upsert_metadata(self.store_path, parse_array_metadata(upgraded))
1635+
object.__setattr__(self.metadata, "_stored_document_upgraded", False)
1636+
16181637
async def _set_selection(
16191638
self,
16201639
indexer: Indexer,
@@ -1623,12 +1642,10 @@ async def _set_selection(
16231642
prototype: BufferPrototype,
16241643
fields: Fields | None = None,
16251644
) -> None:
1626-
if self.metadata._stored_document_upgraded:
1645+
if product(indexer.shape) > 0:
16271646
# Chunks are about to be stored under the upgraded metadata, so store it
16281647
# 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)
1648+
await self._store_upgraded_document()
16321649
return await _set_selection(
16331650
self.store_path,
16341651
self.metadata,
@@ -5827,58 +5844,6 @@ async def _set_selection(
58275844
)
58285845

58295846

5830-
async def _setitem(
5831-
store_path: StorePath,
5832-
metadata: ArrayMetadata,
5833-
codec_pipeline: CodecPipeline,
5834-
config: ArrayConfig,
5835-
chunk_grid: ChunkGrid,
5836-
selection: BasicSelection,
5837-
value: npt.ArrayLike,
5838-
prototype: BufferPrototype | None = None,
5839-
) -> None:
5840-
"""
5841-
Set values in the array using basic indexing.
5842-
5843-
Parameters
5844-
----------
5845-
store_path : StorePath
5846-
The store path of the array.
5847-
metadata : ArrayMetadata
5848-
The array metadata.
5849-
codec_pipeline : CodecPipeline
5850-
The codec pipeline for encoding/decoding.
5851-
config : ArrayConfig
5852-
The array configuration.
5853-
chunk_grid : ChunkGrid
5854-
The chunk grid.
5855-
selection : BasicSelection
5856-
The selection defining the region of the array to set.
5857-
value : npt.ArrayLike
5858-
The values to be written into the selected region of the array.
5859-
prototype : BufferPrototype or None, optional
5860-
A prototype buffer that defines the structure and properties of the array chunks being modified.
5861-
If None, the default buffer prototype is used.
5862-
"""
5863-
if prototype is None:
5864-
prototype = default_buffer_prototype()
5865-
indexer = BasicIndexer(
5866-
selection,
5867-
shape=metadata.shape,
5868-
chunk_grid=chunk_grid,
5869-
)
5870-
return await _set_selection(
5871-
store_path,
5872-
metadata,
5873-
codec_pipeline,
5874-
config,
5875-
chunk_grid,
5876-
indexer,
5877-
value,
5878-
prototype=prototype,
5879-
)
5880-
5881-
58825847
async def _resize(
58835848
array: AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata],
58845849
new_shape: ShapeLike,
@@ -5993,15 +5958,7 @@ async def _append(
59935958
slice(None) if i != axis else slice(old_shape[i], new_shape[i])
59945959
for i in range(len(array.shape))
59955960
)
5996-
await _setitem(
5997-
array.store_path,
5998-
array.metadata,
5999-
array.codec_pipeline,
6000-
array.config,
6001-
array._chunk_grid,
6002-
append_selection,
6003-
data,
6004-
)
5961+
await array.setitem(append_selection, data)
60055962

60065963
return new_shape
60075964

‎src/zarr/core/common.py‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -276,8 +276,13 @@ def _default_zarr_format() -> ZarrFormat:
276276
return cast("ZarrFormat", int(zarr_config.get("default_zarr_format", 3)))
277277

278278

279+
def _subject(name: str, axis: int | None) -> str:
280+
"""`name` as the subject of an error message, prefixed by the dimension `axis`."""
281+
return name[0].upper() + name[1:] if axis is None else f"Dimension {axis}: {name}"
282+
283+
279284
def _parse_positive_int(value: object, name: str, axis: int | None) -> int:
280-
subject = name[0].upper() + name[1:] if axis is None else f"Dimension {axis}: {name}"
285+
subject = _subject(name, axis)
281286
if isinstance(value, bool) or not isinstance(value, int):
282287
raise TypeError(f"{subject} must be an int, got {value!r}")
283288
if value < 1:
@@ -295,10 +300,12 @@ def parse_chunk_edge(size: object, axis: int | None = None) -> int:
295300

296301

297302
def parse_chunk_shape(data: object) -> tuple[int, ...]:
298-
"""Check a regular chunk shape: one chunk edge length per axis (see `parse_chunk_edge`)."""
299-
if not isinstance(data, Iterable):
300-
raise TypeError(f"A chunk shape must be a sequence of chunk edge lengths, got {data!r}")
301-
return tuple(parse_chunk_edge(size, axis) for axis, size in enumerate(data))
303+
"""Check a regular chunk shape: a list or tuple of one chunk edge length per axis
304+
(see `parse_chunk_edge`)."""
305+
match data:
306+
case list() | tuple():
307+
return tuple(parse_chunk_edge(size, axis) for axis, size in enumerate(data))
308+
raise TypeError(f"A chunk shape must be a list or tuple of chunk edge lengths, got {data!r}")
302309

303310

304311
def expand_rle(data: Sequence[object], axis: int | None = None) -> list[int]:
@@ -313,7 +320,8 @@ def expand_rle(data: Sequence[object], axis: int | None = None) -> list[int]:
313320
for item in data:
314321
if isinstance(item, list):
315322
if len(item) != 2:
316-
raise ValueError(f"RLE entries must be an integer or [size, count], got {item}")
323+
subject = _subject("RLE entries", axis)
324+
raise ValueError(f"{subject} must be an integer or [size, count], got {item}")
317325
size, count = item
318326
repeat = _parse_positive_int(count, "RLE repeat count", axis)
319327
result.extend([parse_chunk_edge(size, axis)] * repeat)

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

Lines changed: 92 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,108 @@
11
from __future__ import annotations
22

33
import asyncio
4-
from typing import TYPE_CHECKING
4+
import json
5+
from enum import Enum
6+
from itertools import zip_longest
7+
from typing import TYPE_CHECKING, Final, NamedTuple
58

69
from zarr.abc.store import set_or_delete
10+
from zarr.core._json import buffer_to_json_object
711
from zarr.core.buffer.core import default_buffer_prototype
12+
from zarr.core.buffer.cpu import buffer_prototype as cpu_buffer_prototype
813
from zarr.errors import ContainsArrayError
914
from zarr.storage._common import StorePath, ensure_no_existing_node
1015

1116
if TYPE_CHECKING:
12-
from zarr.core.common import ZarrFormat
17+
from collections.abc import Iterator, Mapping
18+
19+
from zarr.core.buffer import Buffer
20+
from zarr.core.common import JSON, ZarrFormat
1321
from zarr.core.group import GroupMetadata
1422
from zarr.core.metadata import ArrayMetadata
1523

1624

25+
class _Absent(Enum):
26+
ABSENT = "absent"
27+
28+
29+
ABSENT: Final = _Absent.ABSENT
30+
"""Where a `DocumentChange` has no value: the document, member or element is not there."""
31+
32+
33+
class DocumentChange(NamedTuple):
34+
"""A JSON value that differs between a node's stored metadata documents and the
35+
documents its metadata would store."""
36+
37+
path: tuple[str | int, ...]
38+
"""Where the value is: the document's key (e.g. `.zarray`), then the object members
39+
and array indices within it."""
40+
stored: JSON | _Absent
41+
new: JSON | _Absent
42+
43+
44+
def diff_documents(
45+
stored: Mapping[str, JSON], new: Mapping[str, JSON]
46+
) -> tuple[DocumentChange, ...]:
47+
"""What differs between a node's stored metadata documents and the documents its
48+
metadata would store, each keyed by its store key (a document missing from `stored`
49+
is not stored). Empty if they are identical.
50+
51+
Objects and arrays are compared member by member, so a change is the smallest value
52+
that differs; any other two values are identical only if their JSON encodings are, so
53+
`true` differs from `1` and `1.0` from `1`.
54+
"""
55+
return tuple(_diff((), stored, new))
56+
57+
58+
def _diff(
59+
path: tuple[str | int, ...], stored: JSON | _Absent, new: JSON | _Absent
60+
) -> Iterator[DocumentChange]:
61+
match stored, new:
62+
case dict(), dict():
63+
for key in dict.fromkeys([*stored, *new]):
64+
yield from _diff((*path, key), stored.get(key, ABSENT), new.get(key, ABSENT))
65+
case list(), list():
66+
for index, pair in enumerate(zip_longest(stored, new, fillvalue=ABSENT)):
67+
yield from _diff((*path, index), *pair)
68+
case _ if ABSENT in (stored, new) or json.dumps(stored) != json.dumps(new):
69+
yield DocumentChange(path, stored, new)
70+
71+
72+
async def store_documents(store_path: StorePath, documents: Mapping[str, Buffer]) -> None:
73+
"""Store metadata documents encoded by `to_buffer_dict` under `store_path`."""
74+
await asyncio.gather(
75+
*(set_or_delete(store_path / key, value) for key, value in documents.items())
76+
)
77+
78+
79+
async def upsert_metadata(
80+
store_path: StorePath, metadata: ArrayMetadata | GroupMetadata
81+
) -> tuple[DocumentChange, ...]:
82+
"""Store the documents of `metadata` under `store_path` that differ from the stored
83+
ones, and return how they differed (see `diff_documents`): empty if nothing was
84+
stored.
85+
86+
The documents are encoded before the store is read, so metadata that cannot be
87+
stored fails with the store untouched.
88+
"""
89+
documents = metadata.to_buffer_dict(default_buffer_prototype())
90+
stored = await asyncio.gather(
91+
*((store_path / key).get(prototype=cpu_buffer_prototype) for key in documents)
92+
)
93+
changes = diff_documents(
94+
{
95+
key: buffer_to_json_object(buf)
96+
for key, buf in zip(documents, stored, strict=True)
97+
if buf is not None
98+
},
99+
{key: buffer_to_json_object(buf) for key, buf in documents.items()},
100+
)
101+
changed = {change.path[0] for change in changes}
102+
await store_documents(store_path, {k: v for k, v in documents.items() if k in changed})
103+
return changes
104+
105+
17106
def _build_parents(store_path: StorePath, zarr_format: ZarrFormat) -> dict[str, GroupMetadata]:
18107
from zarr.core.group import GroupMetadata
19108

@@ -52,7 +141,7 @@ async def save_metadata(
52141
ValueError
53142
"""
54143
to_save = metadata.to_buffer_dict(default_buffer_prototype())
55-
set_awaitables = [set_or_delete(store_path / key, value) for key, value in to_save.items()]
144+
set_awaitables = [store_documents(store_path, to_save)]
56145

57146
if ensure_parents:
58147
# To enable zarr.create(store, path="a/b/c"), we need to create all the intermediate groups.

0 commit comments

Comments
 (0)