Skip to content

Commit a903d66

Browse files
d-v-bclaude
andcommitted
fix(metadata): warn only where the user must act; guard and refresh upgraded copies
- Readings that give what zarr 3.4.0 read (0/false on an empty axis, JSON true, float rectilinear edges) are silent; the metadata is still marked upgraded, so the first write re-saves it. - JSON true is read as 1 in stored rectilinear edges and RLE sizes and in nested sharding codecs' inner chunk shapes. - A write through a handle whose stored document now lays out chunks differently raises and stores nothing; with no stored document it writes as before. - Storing group metadata refreshes each upgraded consolidated member from its own stored document (the one place: save_metadata); consolidate_metadata no longer needs its own pass. - Metadata built in code with chunk size 0 is read through the upgrades, so an array can be built from it, as in 3.4.0. - Chunk edges in metadata follow the 3.4.0 integer rule (int; bool read as its value); a string or mapping is rejected as a chunk shape as a whole. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b0ea125 commit a903d66

12 files changed

Lines changed: 572 additions & 321 deletions

File tree

‎changes/4334.bugfix.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
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-
`FixedDimension(size=0, ...)` now raises a `ValueError`, so an array can no longer be built directly from metadata with a chunk size of 0; `ArrayV2Metadata(chunks=(0,))` itself is still accepted and written as given. The chunk grid metadata classes read a chunk edge length given as a NumPy integer or a `bool` as the `int` it equals; `RectilinearChunkGridMetadata` used to keep such a value as given, so that it could not be stored (a NumPy integer) or read back (a `bool`). `RectilinearChunkGridMetadata` now rejects a float edge length such as `4.0` with a `TypeError`, as the other metadata classes do; it used to keep it and store it as a JSON float, which the Zarr specification does not allow.
3+
`FixedDimension(size=0, ...)` now raises a `ValueError`. `ArrayV2Metadata(chunks=(0,))` is still accepted and written as given; an array built from such metadata (with `create_hierarchy`, for example) reads the chunk size as a stored chunk size of 0 is read (below). `create_hierarchy` now builds every array and group before it deletes or stores anything, so a node that cannot be built fails with the store untouched. The regular chunk grid metadata class reads a `bool` chunk edge length as the `int` it equals, and rejects a string or a mapping as a chunk shape as a whole. `RectilinearChunkGridMetadata`, which is experimental, now reads a `bool` edge length as the `int` it equals and rejects a NumPy integer or a float edge length such as `4.0` with a `TypeError`; it used to keep them as given, so that it could not store a NumPy integer, could not read back a `bool`, and stored a float as a JSON float, which the Zarr specification does not allow.
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. A stored rectilinear chunk grid whose edge lengths are integral JSON floats (`[[4.0, 2]]`), as zarr-python 3.2 wrote for float edges, is read with those edges as integers, now with a warning; a float anywhere no release wrote one (a regular chunk shape, the inner chunk shape of a sharding codec, a run-length repeat count) is rejected. 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.
5+
Stored metadata with a regular chunk size of 0 or JSON `false` (Zarr format 2 `chunks`, Zarr format 3 `regular` `chunk_shape`) is now 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). On a zero-length axis this opens silently, as before; appending to such an axis then stores chunks of size 1. On an axis of positive length it opens with a `ZarrUserWarning`, which says that the axis holds only the fill value and how to store valid metadata: `array.update_attributes({})`, then `zarr.consolidate_metadata` if the metadata is consolidated. JSON `true`, as zarr-python 3.0 and 3.2 wrote for a chunk size of `True`, is read as 1, silently, in the chunk grid (regular, and the explicit edges and run-length encoded sizes of a rectilinear one) and in the inner chunk shape of every sharding codec, nested or not. A stored rectilinear chunk grid whose edge lengths are integral JSON floats (`[[4.0, 2]]`), as zarr-python 3.2 wrote for float edges, is read with those edges as integers, silently; a float anywhere no release wrote one (a regular chunk shape, the inner chunk shape of a sharding codec, a run-length repeat count, an edge below 1) is rejected.
6+
7+
Writing data to an array read from such metadata (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; in a `ZipStore` this adds a second entry for the metadata document, as every metadata update does. If the metadata the store then holds lays out chunks differently (another writer resized the array keeping the chunk size of 0, say), the write raises a `ValueError` asking to reopen the array, and stores nothing. Storing a group's metadata, which `zarr.consolidate_metadata` and every change to a group with consolidated metadata do, likewise first stores the upgrade of each such member's metadata and consolidates the member's metadata as the store then holds it.

‎src/zarr/api/asynchronous.py‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -231,15 +231,10 @@ 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 = {
235-
k: v async for k, v in group.members(max_depth=None, use_consolidated_for_children=False)
234+
members_metadata = {
235+
k: v.metadata
236+
async for k, v in group.members(max_depth=None, use_consolidated_for_children=False)
236237
}
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()}
243238
# While consolidating, we want to be explicit about when child groups
244239
# are empty by inserting an empty dict for consolidated_metadata.metadata
245240
for k, v in members_metadata.items():

‎src/zarr/core/_json.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ def buffer_to_json(buffer: Buffer) -> JSON:
4141
return cast("JSON", json.loads(buffer.to_bytes()))
4242

4343

44+
def json_equal(a: object, b: object) -> bool:
45+
"""Whether two JSON values have the same JSON encoding. Python compares `True` and
46+
`1`, or `1.0` and `1`, as equal; JSON does not."""
47+
return json.dumps(a) == json.dumps(b)
48+
49+
4450
def buffer_to_json_object(buffer: Buffer) -> dict[str, JSON]:
4551
"""Parse the contents of a `Buffer` as a JSON object (a `dict`).
4652

‎src/zarr/core/array.py‎

Lines changed: 51 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,8 @@
118118
ArrayV2MetadataDict,
119119
ArrayV3Metadata,
120120
)
121-
from zarr.core.metadata.io import save_metadata, upsert_metadata
122-
from zarr.core.metadata.upgrades import upgrade_array_document
121+
from zarr.core.metadata.io import read_stored_array, save_metadata, upsert_metadata
122+
from zarr.core.metadata.upgrades import mark_upgraded, upgrade_array_document
123123
from zarr.core.metadata.v2 import (
124124
CompressorLikev2,
125125
get_object_codec_id,
@@ -202,10 +202,30 @@ def _chunk_sizes_from_shape(
202202
return tuple(result)
203203

204204

205+
def _as_json(value: Any) -> Any:
206+
"""`value`, as `to_dict` returns it, with its tuples as JSON arrays."""
207+
match value:
208+
case tuple() | list():
209+
return [_as_json(item) for item in value]
210+
case dict():
211+
return {key: _as_json(item) for key, item in value.items()}
212+
return value
213+
214+
205215
def parse_array_metadata(data: Any, path: str | None = None) -> ArrayMetadata:
216+
"""Array metadata from a metadata object or a metadata document, naming the array at
217+
`path` in warnings about how an invalid document was read.
218+
219+
The metadata constructors accept chunk sizes that only an invalid document holds
220+
(such as 0), as they always have; such metadata is read as its document is (see
221+
`zarr.core.metadata.upgrades`), so an array can be built from it. No data was read
222+
or written under those chunk sizes, so none of its readings is a warning."""
206223
if isinstance(data, ArrayMetadata):
207-
return data
208-
elif isinstance(data, dict):
224+
document, readings = upgrade_array_document(_as_json(data.to_dict()), data.zarr_format)
225+
if not readings:
226+
return data
227+
return mark_upgraded(parse_array_metadata(dict(document)), [None for _ in readings], path)
228+
if isinstance(data, dict):
209229
zarr_format = data.get("zarr_format")
210230
if zarr_format == 3:
211231
meta_out = ArrayV3Metadata.from_dict(data, path=path)
@@ -1617,22 +1637,31 @@ async def _save_metadata(self, metadata: ArrayMetadata, ensure_parents: bool = F
16171637
await save_metadata(self.store_path, metadata, ensure_parents=ensure_parents)
16181638

16191639
async def _store_upgraded_document(self) -> None:
1620-
"""Store the upgrade of this array's current stored document, if it needs one.
1640+
"""Store the upgrade of this array's current stored document, if it needs one,
1641+
before chunks are written under this handle's metadata.
16211642
16221643
Only for metadata read from a document that had to be upgraded (see
16231644
`zarr.core.metadata.upgrades`). The document is read again, because the store may
1624-
hold a newer one than this handle's metadata: if that one needs no upgrade (the
1625-
array was re-saved or resized since, possibly by another implementation), it is
1626-
left as written. Storing the same upgrade twice is harmless, so concurrent
1627-
callers need no coordination.
1645+
hold a newer one than this handle's metadata. If that one lays out chunks
1646+
differently (the array was resized since by software that kept the invalid chunk
1647+
size), this handle would write chunks no reader finds, so it raises and stores
1648+
nothing. If it needs no upgrade (the array was re-saved since, possibly by another
1649+
implementation), it is left as written; if there is none, there is nothing to
1650+
upgrade. Storing the same upgrade twice is harmless, so concurrent callers need
1651+
no coordination.
16281652
"""
16291653
if not self.metadata._stored_document_upgraded:
16301654
return
1631-
zarr_format = self.metadata.zarr_format
1632-
stored = await get_array_metadata(self.store_path, zarr_format=zarr_format)
1633-
upgraded, readings = upgrade_array_document(stored, zarr_format)
1634-
if readings:
1635-
await upsert_metadata(self.store_path, parse_array_metadata(upgraded))
1655+
read = await read_stored_array(self.store_path, self.metadata.zarr_format)
1656+
if read is not None:
1657+
current, upgraded = read
1658+
if _chunk_layout(current) != _chunk_layout(self.metadata):
1659+
raise ValueError(
1660+
f"The metadata stored for the array at {str(self.store_path)!r} has "
1661+
"changed since this array was opened: reopen the array to write to it."
1662+
)
1663+
if upgraded:
1664+
await upsert_metadata(self.store_path, current)
16361665
object.__setattr__(self.metadata, "_stored_document_upgraded", False)
16371666

16381667
async def _set_selection(
@@ -4864,6 +4893,14 @@ async def create_array(
48644893
)
48654894

48664895

4896+
def _chunk_layout(metadata: ArrayMetadata) -> tuple[object, tuple[int, ...] | None]:
4897+
"""How an array's chunks are laid out: its chunk grid and, if it is sharded, the
4898+
inner chunk shape."""
4899+
grid = metadata.chunks if isinstance(metadata, ArrayV2Metadata) else metadata.chunk_grid
4900+
sharding = _sharding_codec(metadata)
4901+
return grid, None if sharding is None else sharding.chunk_shape
4902+
4903+
48674904
def _sharding_codec(metadata: ArrayMetadata) -> ShardingCodec | None:
48684905
"""The array's sharding codec, or None if the array is not sharded.
48694906

‎src/zarr/core/common.py‎

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

33
import asyncio
44
import math
5-
import numbers
65
import warnings
76
from collections.abc import Iterable, Mapping, Sequence
87
from enum import Enum
@@ -283,22 +282,20 @@ def _subject(name: str, axis: int | None) -> str:
283282

284283

285284
def _parse_positive_int(value: object, name: str, axis: int | None) -> int:
286-
"""`value` as an `int` of at least 1. An integer of any integer type (an `int`, a
287-
`bool` or a NumPy integer) is read as the `int` it equals; a float is rejected, even
288-
an integral one (stored documents with integral floats are read by
289-
`zarr.core.metadata.upgrades`)."""
285+
"""`value` as an `int` of at least 1. A `bool` is read as the `int` it equals; any
286+
other type, a NumPy integer or a float (even an integral one: stored documents with
287+
integral floats are read by `zarr.core.metadata.upgrades`), is rejected."""
290288
subject = _subject(name, axis)
291-
if not isinstance(value, numbers.Integral):
292-
raise TypeError(f"{subject} must be an integer, got {value!r}")
293-
parsed = int(value)
294-
if parsed < 1:
289+
if not isinstance(value, int):
290+
raise TypeError(f"{subject} must be an int, got {value!r}")
291+
if value < 1:
295292
raise ValueError(f"{subject} must be >= 1, got {value!r}")
296-
return parsed
293+
return int(value)
297294

298295

299296
def parse_chunk_edge(size: object, axis: int | None = None) -> int:
300-
"""Check that `size` is a chunk edge length: an integer of at least 1, read as an
301-
`int`.
297+
"""Check that `size` is a chunk edge length: an `int` of at least 1 (a `bool` is
298+
read as the `int` it equals).
302299
303300
This is the one rule for chunk edge lengths in metadata: bare chunk sizes, explicit
304301
edges and run-length encoded sizes. `axis`, when given, is named in the error.
@@ -307,9 +304,11 @@ def parse_chunk_edge(size: object, axis: int | None = None) -> int:
307304

308305

309306
def parse_chunk_shape(data: object) -> tuple[int, ...]:
310-
"""Check a regular chunk shape: an iterable of one chunk edge length per axis
311-
(see `parse_chunk_edge`)."""
307+
"""Check a regular chunk shape: an iterable, other than a string or a mapping, of one
308+
chunk edge length per axis (see `parse_chunk_edge`)."""
312309
match data:
310+
case str() | Mapping():
311+
pass
313312
case Iterable():
314313
return tuple(parse_chunk_edge(size, axis) for axis, size in enumerate(data))
315314
raise TypeError(f"A chunk shape must be an iterable of chunk edge lengths, got {data!r}")

‎src/zarr/core/group.py‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313

1414
import zarr.api.asynchronous as async_api
1515
from zarr.abc.metadata import Metadata
16-
from zarr.abc.store import Store, set_or_delete
1716
from zarr.core._info import GroupInfo
1817
from zarr.core._json import buffer_to_json_object, json_to_buffer
1918
from zarr.core.array import (
@@ -75,6 +74,7 @@
7574
)
7675
from typing import Any
7776

77+
from zarr.abc.store import Store
7878
from zarr.core.array_spec import ArrayConfigLike
7979
from zarr.core.buffer import Buffer, BufferPrototype
8080
from zarr.core.chunk_key_encodings import ChunkKeyEncodingLike
@@ -2115,9 +2115,7 @@ async def update_attributes_async(self, new_attributes: dict[str, Any]) -> Group
21152115
new_metadata = replace(self.metadata, attributes=new_attributes)
21162116

21172117
# Write new metadata
2118-
to_save = new_metadata.to_buffer_dict(default_buffer_prototype())
2119-
awaitables = [set_or_delete(self.store_path / key, value) for key, value in to_save.items()]
2120-
await asyncio.gather(*awaitables)
2118+
await save_metadata(self.store_path, new_metadata)
21212119

21222120
async_group = replace(self._async_group, metadata=new_metadata)
21232121
return replace(self, _async_group=async_group)

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

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
from __future__ import annotations
22

33
import asyncio
4-
import json
4+
from dataclasses import replace
55
from enum import Enum
66
from itertools import zip_longest
77
from typing import TYPE_CHECKING, Final, NamedTuple
88

99
from zarr.abc.store import set_or_delete
10-
from zarr.core._json import buffer_to_json_object
10+
from zarr.core._json import buffer_to_json_object, json_equal
1111
from zarr.core.buffer.core import default_buffer_prototype
1212
from zarr.core.buffer.cpu import buffer_prototype as cpu_buffer_prototype
13-
from zarr.errors import ContainsArrayError
13+
from zarr.core.metadata.upgrades import upgrade_array_document
14+
from zarr.errors import ArrayNotFoundError, ContainsArrayError
1415
from zarr.storage._common import StorePath, ensure_no_existing_node
1516

1617
if TYPE_CHECKING:
@@ -65,7 +66,7 @@ def _diff(
6566
case list(), list():
6667
for index, pair in enumerate(zip_longest(stored, new, fillvalue=ABSENT)):
6768
yield from _diff((*path, index), *pair)
68-
case _ if ABSENT in (stored, new) or json.dumps(stored) != json.dumps(new):
69+
case _ if ABSENT in (stored, new) or not json_equal(stored, new):
6970
yield DocumentChange(path, stored, new)
7071

7172

@@ -103,6 +104,49 @@ async def upsert_metadata(
103104
return changes
104105

105106

107+
async def read_stored_array(
108+
store_path: StorePath, zarr_format: ZarrFormat
109+
) -> tuple[ArrayMetadata, bool] | None:
110+
"""The metadata of the array document stored at `store_path` as it now is, read with
111+
the upgrades but without their warnings (the handle that asks has warned), and
112+
whether the document had to be upgraded; `None` if no array document is stored
113+
there."""
114+
from zarr.core.array import get_array_metadata, parse_array_metadata
115+
116+
try:
117+
stored = await get_array_metadata(store_path, zarr_format=zarr_format)
118+
except ArrayNotFoundError:
119+
return None
120+
upgraded, readings = upgrade_array_document(stored, zarr_format)
121+
return parse_array_metadata(upgraded, str(store_path)), bool(readings)
122+
123+
124+
async def _refresh_consolidated(store_path: StorePath, metadata: GroupMetadata) -> GroupMetadata:
125+
"""`metadata` with each member of its consolidated metadata that was read from a
126+
document that had to be upgraded replaced by the metadata of the member's own
127+
document as it now is, after storing that document's upgrade if it needs one: the
128+
member document may have changed since, so the consolidated copy is never stored
129+
as if it were valid."""
130+
from zarr.core.group import GroupMetadata
131+
132+
consolidated = metadata.consolidated_metadata
133+
if consolidated is None:
134+
return metadata
135+
members = dict(consolidated.metadata)
136+
for name, member in consolidated.metadata.items():
137+
if isinstance(member, GroupMetadata):
138+
members[name] = await _refresh_consolidated(store_path / name, member)
139+
elif member._stored_document_upgraded:
140+
read = await read_stored_array(store_path / name, member.zarr_format)
141+
if read is not None:
142+
members[name], upgraded = read
143+
if upgraded:
144+
await upsert_metadata(store_path / name, members[name])
145+
if all(members[name] is member for name, member in consolidated.metadata.items()):
146+
return metadata
147+
return replace(metadata, consolidated_metadata=replace(consolidated, metadata=members))
148+
149+
106150
def _build_parents(store_path: StorePath, zarr_format: ZarrFormat) -> dict[str, GroupMetadata]:
107151
from zarr.core.group import GroupMetadata
108152

@@ -140,6 +184,11 @@ async def save_metadata(
140184
------
141185
ValueError
142186
"""
187+
from zarr.core.group import GroupMetadata
188+
189+
if isinstance(metadata, GroupMetadata):
190+
# The one place group metadata is stored, and with it consolidated metadata.
191+
metadata = await _refresh_consolidated(store_path, metadata)
143192
to_save = metadata.to_buffer_dict(default_buffer_prototype())
144193
set_awaitables = [store_documents(store_path, to_save)]
145194

0 commit comments

Comments
 (0)