Skip to content

Commit 5dccfb8

Browse files
d-v-bclaude
andcommitted
fix(metadata): recommend recreating an array whose stored chunk size was 0
The warning for a stored chunk size of 0 on an axis of positive length now says that the array holds only its fill value, so recreating it with the wanted chunk shape loses nothing, and gives the re-save as the way to keep it instead. A re-save freezes the smallest chunk size into an array that holds no data yet. Each reading now carries its own advice, so mark_upgraded appends no shared hint. Assisted-by: ClaudeCode:claude-fable-5-1 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 9e07aaf commit 5dccfb8

3 files changed

Lines changed: 29 additions & 23 deletions

File tree

‎changes/4334.bugfix.md‎

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

33
`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` (Zarr format 2 `chunks`, Zarr format 3 `regular` `chunk_shape`) is now read as chunk size 1 (the inner chunk size for sharded arrays, which previously failed to open), however long the axis is: that is the chunk size `chunks=-1` gives on a zero-length axis, and it does not depend on how far the axis has grown since. 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, and appending to it 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.
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 chunk size 1 (the inner chunk size for sharded arrays, which previously failed to open), however long the axis is: that is the chunk size `chunks=-1` gives on a zero-length axis, and it does not depend on how far the axis has grown since. 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, and appending to it stores chunks of size 1. On an axis of positive length it opens with a `ZarrUserWarning`, which says that the array holds only its fill value, so that recreating it with the wanted chunk shape loses nothing, and how to keep it by storing valid metadata instead: `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.
66

77
Writing data to an array whose stored metadata holds a regular chunk size of 0 or `false` (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 (a `true` chunk size or an integral float edge is read as the value it equals, so a write stores no metadata for it); 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 stored a different chunk size since, say), the write raises a `ValueError` asking to reopen the array, and stores nothing. Apart from the array's own metadata writes (`update_attributes`, `resize`), which store the upgrade as before, this is the only operation that stores it: a group's consolidated metadata keeps such an array's metadata as it was stored (`zarr.consolidate_metadata` copies it as the array's own document holds it) until the array stores its upgrade through the group's handle, and changing a group reads and writes no metadata of its members.

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

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -50,11 +50,15 @@ class Reading(NamedTuple):
5050
"""Returns `None` if the document needs no upgrade, else the upgraded document and how
5151
it was read."""
5252

53-
RESAVE_HINT: Final = (
54-
"To store valid metadata, open the array writable and call `array.update_attributes({})`; "
55-
"if a group holds consolidated metadata for the array, then also call "
56-
"`zarr.consolidate_metadata` on that group."
53+
RECREATE_HINT: Final = (
54+
"The array holds only its fill value, so recreate it with the chunk shape you want; "
55+
"nothing is lost. To keep it instead, store valid metadata: open the array writable and "
56+
"call `array.update_attributes({})`; if a group holds consolidated metadata for the "
57+
"array, then also call `zarr.consolidate_metadata` on that group."
5758
)
59+
"""How to act on a document whose array can hold no data: a stored chunk size of 0 is read
60+
as the smallest chunk size, which is a poor chunk shape for the data the array grows into,
61+
and a re-save would keep it."""
5862

5963

6064
def mark_upgraded[M](
@@ -69,16 +73,17 @@ def mark_upgraded[M](
6973
upgrades whose `readings` `upgrade_array_document` returned, if any. If a reading
7074
moves chunks, keep a copy of `stored` as `_stored_document` on `metadata`, so the
7175
array stores the upgrade before it writes chunks under it and consolidated metadata
72-
stores it as it was stored. If `warn`, warn once with the readings' warnings,
73-
naming the array at `path` when the caller knows it."""
76+
stores it as it was stored. If `warn`, warn once with the readings' warnings (each
77+
says what the user must act on and how), naming the array at `path` when the caller
78+
knows it."""
7479
if any(reading.moves_chunks for reading in readings):
7580
object.__setattr__(metadata, "_stored_document", copy.deepcopy(stored))
7681
messages = [reading.warning for reading in readings if reading.warning is not None]
7782
if warn and messages:
7883
subject = "" if path is None else f"Array {path!r}: "
7984
# The synchronous API parses metadata on zarr's IO thread, whose stack holds no
8085
# user code, so the warning points at the `from_dict` that read the document.
81-
warnings.warn(f"{subject}{' '.join(messages)} {RESAVE_HINT}", ZarrUserWarning, stacklevel=2)
86+
warnings.warn(f"{subject}{' '.join(messages)}", ZarrUserWarning, stacklevel=2)
8287
return metadata
8388

8489

@@ -116,11 +121,10 @@ def _read_chunk_size(
116121
unit,
117122
True,
118123
(
119-
"1, as no chunk can be stored under a chunk size of 0, so the array "
120-
"holds only its fill value"
124+
"1, as no chunk can be stored under a chunk size of 0"
121125
if unit == 1
122126
else f"{unit}, the inner chunk size, as no chunk can be stored under a "
123-
"chunk size of 0, so the array holds only its fill value"
127+
"chunk size of 0"
124128
),
125129
)
126130
return None
@@ -133,8 +137,9 @@ def _read_chunk_shape(
133137
axes of lengths `spans` whose chunks are multiples of `units` (1 where not given).
134138
135139
Returns the chunk shape and how it was read, if any entry was read as another value
136-
(the warning is a sentence saying how the chunk shape was read); `None` if it cannot
137-
be read or needs no upgrade.
140+
(the warning says how the chunk shape was read and, as the array then holds only its
141+
fill value, recommends recreating it, see `RECREATE_HINT`); `None` if it cannot be
142+
read or needs no upgrade.
138143
"""
139144
if not (isinstance(stored, list) and len(stored) == len(spans)):
140145
return None
@@ -156,7 +161,8 @@ def _read_chunk_shape(
156161
return None
157162
warning = (
158163
f"The stored chunk shape {json.dumps(stored)} is invalid: chunk sizes must be "
159-
f"integers of at least 1. It is read as {edges}, reading {'; '.join(readings)}."
164+
f"integers of at least 1. It is read as {edges}, reading {'; '.join(readings)}. "
165+
f"{RECREATE_HINT}"
160166
if readings
161167
else None
162168
)

‎tests/test_metadata/test_upgrades.py‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from zarr.core.group import ConsolidatedMetadata
2121
from zarr.core.metadata import ArrayV2Metadata, ArrayV3Metadata
2222
from zarr.core.metadata.upgrades import (
23-
RESAVE_HINT,
23+
RECREATE_HINT,
2424
upgrade_array_document,
2525
)
2626
from zarr.core.metadata.v3 import RectilinearChunkGridMetadata, RegularChunkGridMetadata
@@ -128,28 +128,27 @@ def _nested_sharded_doc(inner: list[Any], nested: list[Any]) -> dict[str, JSON]:
128128
"moved",
129129
(
130130
r"^The stored chunk shape \[0\] is invalid: .* read as \[1\], reading 0 in "
131-
r"dimension 0 as 1, as no chunk can be stored under a chunk size of 0, so the "
132-
r"array holds only its fill value\.$"
131+
r"dimension 0 as 1, as no chunk can be stored under a chunk size of 0\.$"
133132
),
134133
),
135134
(
136135
_v3_doc([4, 3], [4, 0]),
137136
((4, 1),),
138137
"moved",
139-
r"reading 0 in dimension 1 as .* holds only its fill value\.$",
138+
r"reading 0 in dimension 1 as .* under a chunk size of 0\.$",
140139
),
141140
(
142141
_v2_doc([0, 3], [0, 0]),
143142
((1, 1),),
144143
"moved",
145-
r"read as \[1, 1\], reading 0 in dimension 1 as .* holds only its fill value\.$",
144+
r"read as \[1, 1\], reading 0 in dimension 1 as .* under a chunk size of 0\.$",
146145
),
147146
(_v3_doc([0], [0], inner=[4]), ((4,), (4,)), "moved", None),
148147
(
149148
_v3_doc([10], [0], inner=[4]),
150149
((4,), (4,)),
151150
"moved",
152-
r"as 4, the inner chunk size, as no chunk .* holds only its fill value",
151+
r"as 4, the inner chunk size, as no chunk can be stored under a chunk size of 0",
153152
),
154153
(_v3_doc([0, 3], [0, 3], inner=[2, 3]), ((2, 3), (2, 3)), "moved", None),
155154
(_v3_doc([5], [True], inner=[True]), ((1,), (1,)), "respelled", None),
@@ -188,7 +187,8 @@ def test_upgrade_array_document(
188187
chunk size read as another size), so the array stores the upgrade before it writes
189188
chunks, but not one that only respells a value (`true` as 1). It warns once, naming
190189
the array, only where a chunk size of 0 was stored for a non-empty axis (which then
191-
holds only its fill value), saying how that part was read and how to re-save. The
190+
holds only its fill value), saying how that part was read and that recreating the
191+
array loses nothing (see `RECREATE_HINT`). The
192192
other readings give what zarr read before, so they are silent."""
193193
upgraded_doc, readings = upgrade_array_document(doc, cast("ZarrFormat", doc["zarr_format"]))
194194
assert {
@@ -209,9 +209,9 @@ def test_upgrade_array_document(
209209
else:
210210
[message] = messages
211211
assert message.startswith("Array 'group/array': ")
212-
assert message.endswith(RESAVE_HINT)
212+
assert message.endswith(RECREATE_HINT)
213213
assert re.search(
214-
warning, message.removeprefix("Array 'group/array': ").removesuffix(f" {RESAVE_HINT}")
214+
warning, message.removeprefix("Array 'group/array': ").removesuffix(f" {RECREATE_HINT}")
215215
)
216216

217217

0 commit comments

Comments
 (0)