Skip to content

Commit 4c4fe21

Browse files
d-v-bclaude
andcommitted
fix(metadata): read float edges only in stored rectilinear documents
The patch release widened the one chunk edge rule to accept integral floats so that stored rectilinear grids written with float edges (`[[4.0, 2]]`, as zarr 3.2 wrote for float edges) keep opening. That also made a stored regular chunk shape `[10.0]` open, which zarr 3.4.0 rejected and the next minor release would reject again. The constructor rule now accepts integers of any integer type (`int`, `bool`, NumPy integers) and rejects floats. A new document upgrade reads an integral JSON float of at least 1 as an `int` where zarr 3.2 stored one: the explicit edges and run-length encoded sizes of a rectilinear chunk grid, with the standard warning. Bare sizes, repeat counts, regular chunk shapes and inner chunk shapes stay for the constructors to reject. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 2d0121d commit 4c4fe21

5 files changed

Lines changed: 206 additions & 25 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-
`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, a `bool` or an integral float 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`).
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.
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 (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` 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.

‎src/zarr/core/common.py‎

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -283,24 +283,22 @@ def _subject(name: str, axis: int | None) -> str:
283283

284284

285285
def _parse_positive_int(value: object, name: str, axis: int | None) -> int:
286-
"""`value` as an `int` of at least 1. Any integral number is read as the `int` it
287-
equals: an `int`, a `bool`, a NumPy integer or an integral float."""
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`)."""
288290
subject = _subject(name, axis)
289-
match value:
290-
case numbers.Integral():
291-
parsed = int(value)
292-
case float() if value.is_integer():
293-
parsed = int(value)
294-
case _:
295-
raise TypeError(f"{subject} must be an integer, got {value!r}")
291+
if not isinstance(value, numbers.Integral):
292+
raise TypeError(f"{subject} must be an integer, got {value!r}")
293+
parsed = int(value)
296294
if parsed < 1:
297295
raise ValueError(f"{subject} must be >= 1, got {value!r}")
298296
return parsed
299297

300298

301299
def parse_chunk_edge(size: object, axis: int | None = None) -> int:
302-
"""Check that `size` is a chunk edge length: an integral number of at least 1, read
303-
as an `int`.
300+
"""Check that `size` is a chunk edge length: an integer of at least 1, read as an
301+
`int`.
304302
305303
This is the one rule for chunk edge lengths in metadata: bare chunk sizes, explicit
306304
edges and run-length encoded sizes. `axis`, when given, is named in the error.

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

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,12 @@ def _is_int_list(value: object) -> TypeGuard[list[int]]:
5757
return isinstance(value, list) and all(isinstance(v, int) for v in value)
5858

5959

60+
def _abbreviate(value: JSON, limit: int = 60) -> str:
61+
"""`value` as JSON, cut to at most `limit` characters."""
62+
text = json.dumps(value)
63+
return text if len(text) <= limit else f"{text[: limit - 3]}..."
64+
65+
6066
def _read_chunk_size(size: JSON, span: int | None, unit: int) -> tuple[int, str | None] | None:
6167
"""Read one entry of a stored regular chunk shape as a chunk edge length.
6268
@@ -180,9 +186,61 @@ def _invalid_chunk_sizes_v3(doc: ArrayDocument) -> tuple[ArrayDocument, str] | N
180186
return None
181187

182188

189+
def _read_edge_length(edge: JSON) -> JSON:
190+
"""Read one stored chunk edge length of a rectilinear chunk grid: an integral JSON
191+
float of at least 1 (`4.0`) is read as the `int` it equals. Anything else is kept,
192+
for the metadata constructors to check."""
193+
match edge:
194+
case float() if edge.is_integer() and edge >= 1:
195+
return int(edge)
196+
return edge
197+
198+
199+
def _read_rectilinear_axis(spec: JSON) -> JSON:
200+
"""Read the stored chunk edge lengths of one axis of a rectilinear chunk grid (see
201+
`_read_edge_length`): its explicit edges and the sizes of its run-length encoded
202+
`[size, count]` pairs. A bare chunk size and a repeat count are kept as stored: no
203+
writer stored them as floats."""
204+
match spec:
205+
case list():
206+
return [_read_rectilinear_entry(entry) for entry in spec]
207+
return spec
208+
209+
210+
def _read_rectilinear_entry(entry: JSON) -> JSON:
211+
match entry:
212+
case [size, count]:
213+
return [_read_edge_length(size), count]
214+
return _read_edge_length(entry)
215+
216+
217+
def _float_edge_lengths_v3(doc: ArrayDocument) -> tuple[ArrayDocument, str] | None:
218+
grid = doc.get("chunk_grid")
219+
if not (isinstance(grid, Mapping) and grid.get("name") == "rectilinear"):
220+
return None
221+
configuration = grid.get("configuration")
222+
if not isinstance(configuration, Mapping):
223+
return None
224+
stored = configuration.get("chunk_shapes")
225+
if not isinstance(stored, list):
226+
return None
227+
read = [_read_rectilinear_axis(axis) for axis in stored]
228+
# An integral float and the `int` it equals compare equal, but not as JSON text.
229+
axes = [axis for axis, spec in enumerate(stored) if json.dumps(spec) != json.dumps(read[axis])]
230+
if not axes:
231+
return None
232+
reading = (
233+
f"The stored chunk edge lengths {_abbreviate(stored)} are invalid: chunk edge "
234+
f"lengths must be integers. They are read as {_abbreviate(read)}, reading each "
235+
f"edge length stored as a float, in dimensions {axes}, as the integer it equals."
236+
)
237+
upgraded = {**configuration, "chunk_shapes": read}
238+
return {**doc, "chunk_grid": {**grid, "configuration": upgraded}}, reading
239+
240+
183241
ARRAY_UPGRADES: Final[Mapping[ZarrFormat, tuple[Upgrade, ...]]] = {
184242
2: (_invalid_chunk_sizes_v2,),
185-
3: (_invalid_inner_chunk_sizes_v3, _invalid_chunk_sizes_v3),
243+
3: (_invalid_inner_chunk_sizes_v3, _invalid_chunk_sizes_v3, _float_edge_lengths_v3),
186244
}
187245
"""The upgrades of an array document of each Zarr format, applied in order."""
188246

‎tests/test_metadata/test_upgrades.py‎

Lines changed: 124 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def _v2_doc(shape: list[int], chunks: list[Any]) -> dict[str, JSON]:
4747

4848

4949
def _v3_doc(
50-
shape: list[int], chunk_shape: list[Any], inner: list[int] | None = None
50+
shape: list[int], chunk_shape: list[Any], inner: list[Any] | None = None
5151
) -> dict[str, JSON]:
5252
bytes_codec: dict[str, JSON] = {"name": "bytes", "configuration": {"endian": "little"}}
5353
codecs: list[JSON] = [bytes_codec]
@@ -240,6 +240,116 @@ def test_stored_fractional_chunk_size_rejected() -> None:
240240
_read_strictly(_v3_doc([4], [4.5]))
241241

242242

243+
def _rectilinear_doc(shape: list[int], chunk_shapes: list[Any]) -> dict[str, JSON]:
244+
return _v3_doc(shape, [1] * len(shape)) | {
245+
"chunk_grid": {
246+
"name": "rectilinear",
247+
"configuration": {"kind": "inline", "chunk_shapes": chunk_shapes},
248+
}
249+
}
250+
251+
252+
@pytest.mark.parametrize(
253+
("chunk_shapes", "expected", "warning"),
254+
[
255+
([[[4, 2]], [[5, 2]]], ((4, 4), (5, 5)), None),
256+
(
257+
[[[4.0, 2]], [[5, 2]]],
258+
((4, 4), (5, 5)),
259+
(
260+
r"^The stored chunk edge lengths \[\[\[4\.0, 2\]\], \[\[5, 2\]\]\] are "
261+
r"invalid: .* read as \[\[\[4, 2\]\], \[\[5, 2\]\]\], .* in dimensions \[0\],"
262+
),
263+
),
264+
([[3.0, 5.0], [[5, 2]]], ((3, 5), (5, 5)), r"read as \[\[3, 5\], "),
265+
([[[4.0, 2], 2.0], [[5, 2]]], ((4, 4, 2), (5, 5)), r"read as \[\[\[4, 2\], 2\], "),
266+
([[[4.0, 2]], [10]], ((4, 4), (10,)), r"read as \[\[\[4, 2\]\], \[10\]\]"),
267+
([[[4.0, 2]], [5.0, 5]], ((4, 4), (5, 5)), r"in dimensions \[0, 1\],"),
268+
],
269+
ids=["valid", "rle-size", "edges", "rle-size-and-edge", "sharded-outer", "2d"],
270+
)
271+
def test_read_float_edges_in_rectilinear_grid(
272+
chunk_shapes: list[Any],
273+
expected: tuple[tuple[int, ...], ...],
274+
warning: str | None,
275+
) -> None:
276+
"""A stored rectilinear chunk grid whose explicit edges or run-length encoded sizes
277+
are integral floats, as zarr-python wrote them when given float edges, is read with
278+
those edges as `int`s; `from_dict` warns once, naming the array and the dimensions,
279+
and how to re-save."""
280+
shape = [sum(edges) for edges in expected]
281+
doc = _rectilinear_doc(shape, chunk_shapes)
282+
with (
283+
zarr.config.set({"array.rectilinear_chunks": True}),
284+
warnings.catch_warnings(record=True) as record,
285+
):
286+
warnings.simplefilter("always")
287+
metadata = ArrayV3Metadata.from_dict(doc, path="group/array")
288+
assert metadata.chunk_grid == RectilinearChunkGridMetadata(chunk_shapes=expected)
289+
messages = [str(w.message) for w in record]
290+
if warning is None:
291+
assert messages == []
292+
else:
293+
[message] = messages
294+
assert message.startswith("Array 'group/array': ")
295+
assert re.search(warning, message.removeprefix("Array 'group/array': "))
296+
assert message.endswith(RESAVE_HINT)
297+
298+
299+
@pytest.mark.parametrize(
300+
("doc", "error"),
301+
[
302+
(_v3_doc([20], [10.0]), "Dimension 0: chunk edge length must be an integer, got 10.0"),
303+
(
304+
_v3_doc([8], [4], inner=[2.0]),
305+
"Expected an iterable of integers. Got [2.0] instead.",
306+
),
307+
(_v2_doc([20], [10.0]), "Expected an iterable of integers. Got [10.0] instead."),
308+
(
309+
_rectilinear_doc([8], [[[4, 2.0]]]),
310+
"Dimension 0: RLE repeat count must be an integer, got 2.0",
311+
),
312+
(
313+
_rectilinear_doc([8], [4.0]),
314+
"Dimension 0: chunk edge length must be an integer, got 4.0",
315+
),
316+
],
317+
ids=["regular", "sharding-inner", "v2", "rle-count", "rectilinear-bare"],
318+
)
319+
def test_stored_float_chunk_size_rejected(doc: dict[str, JSON], error: str) -> None:
320+
"""A float chunk size is read only where zarr-python stored one, as the edges of a
321+
rectilinear chunk grid. Anywhere else it is rejected, as zarr 3.4.0 rejected a
322+
stored regular chunk size of `10.0`."""
323+
with zarr.config.set({"array.rectilinear_chunks": True}), pytest.raises(TypeError) as info:
324+
_read_strictly(doc)
325+
assert info.match(re.escape(error))
326+
327+
328+
def test_float_edges_round_trip(tmp_path: Path) -> None:
329+
"""A store whose rectilinear chunk grid holds the float edges zarr-python wrote opens
330+
with a warning, reads its data and re-saves the edges as `int`s."""
331+
path = tmp_path / "float.zarr"
332+
data = np.arange(80, dtype="int16").reshape(8, 10)
333+
with zarr.config.set({"array.rectilinear_chunks": True}):
334+
zarr.create_array(path, shape=data.shape, chunks=[[4, 4], [5, 5]], dtype="int16")[...] = (
335+
data
336+
)
337+
338+
def store_floats(doc: dict[str, Any]) -> None:
339+
doc["chunk_grid"]["configuration"]["chunk_shapes"] = [[[4.0, 2]], [[5, 2]]]
340+
341+
_rewrite_doc(path, 3, store_floats)
342+
with pytest.warns(ZarrUserWarning, match=r"read as \[\[\[4, 2\]\], \[\[5, 2\]\]\]"):
343+
arr = zarr.open_array(path, mode="a")
344+
np.testing.assert_array_equal(arr[...], data)
345+
arr.update_attributes({})
346+
stored = json.loads((path / "zarr.json").read_text())["chunk_grid"]["configuration"]
347+
assert json.dumps(stored["chunk_shapes"]) == "[[[4, 2]], [[5, 2]]]"
348+
with warnings.catch_warnings():
349+
warnings.simplefilter("error", ZarrUserWarning)
350+
np.testing.assert_array_equal(zarr.open_array(path)[...], data)
351+
352+
243353
def test_v2_constructor_rejects_chunks_of_wrong_length() -> None:
244354
with pytest.raises(ValueError, match="`chunks` has length 1, but `shape` has length 2"):
245355
ArrayV2Metadata(shape=(4, 4), chunks=(2,), dtype=Int16(), fill_value=0, order="C")
@@ -284,20 +394,26 @@ def _second_edge(grid: RectilinearChunkGridMetadata) -> int:
284394
@pytest.mark.parametrize("site", CHUNK_EDGE_SITES)
285395
@pytest.mark.parametrize(
286396
("size", "expected"),
287-
[(4, 4), (True, 1), (np.int64(4), 4), (4.0, 4), (np.float64(4.0), 4)],
288-
ids=["int", "bool", "numpy-int", "float", "numpy-float"],
397+
[(4, 4), (True, 1), (np.int64(4), 4)],
398+
ids=["int", "bool", "numpy-int"],
289399
)
290-
def test_metadata_reads_integral_chunk_edge(site: str, size: object, expected: int) -> None:
291-
"""Chunk grid metadata reads any integral number as the `int` chunk edge length it
292-
equals."""
400+
def test_metadata_reads_integer_chunk_edge(site: str, size: object, expected: int) -> None:
401+
"""Chunk grid metadata reads an integer of any integer type as the `int` chunk edge
402+
length it equals."""
293403
edge = CHUNK_EDGE_SITES[site](size)
294404
assert type(edge) is int
295405
assert edge == expected
296406

297407

298408
@pytest.mark.parametrize("site", CHUNK_EDGE_SITES)
299-
@pytest.mark.parametrize("size", [4.5, float("inf"), "4", None])
300-
def test_metadata_rejects_non_integral_chunk_edge(site: str, size: object) -> None:
409+
@pytest.mark.parametrize(
410+
"size",
411+
[4.0, np.float64(4.0), 4.5, float("inf"), "4", None],
412+
ids=["float", "numpy-float", "fractional", "inf", "str", "none"],
413+
)
414+
def test_metadata_rejects_non_integer_chunk_edge(site: str, size: object) -> None:
415+
"""A float is not a chunk edge length in metadata built in code, even an integral
416+
one; stored documents with integral floats are read by the upgrades."""
301417
with pytest.raises(
302418
TypeError,
303419
match=re.escape(f"Dimension 0: chunk edge length must be an integer, got {size!r}"),

‎tests/test_unified_chunk_grid.py‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -494,7 +494,6 @@ def test_chunk_grid_iter() -> None:
494494
[
495495
([[10, 3]], [10, 10, 10]),
496496
([[10, 2], [20, 1]], [10, 10, 20]),
497-
([4.0, [4.0, 2], [5, 2.0]], [4, 4, 4, 5, 5]),
498497
([[True, 2], [np.int64(3), np.int64(1)]], [1, 1, 3]),
499498
],
500499
)
@@ -553,13 +552,23 @@ def test_rle_expand_rejects_invalid(rle_input: list[Any], match: str) -> None:
553552
("rle_input", "match"),
554553
[
555554
([10.5], "Chunk edge length must be an integer, got 10.5"),
555+
([10.0], "Chunk edge length must be an integer, got 10.0"),
556+
([[10.0, 3]], "Chunk edge length must be an integer, got 10.0"),
556557
(["10"], "Chunk edge length must be an integer, got '10'"),
557558
([[10, 3.5]], "RLE repeat count must be an integer, got 3.5"),
559+
([[10, 3.0]], "RLE repeat count must be an integer, got 3.0"),
560+
],
561+
ids=[
562+
"fractional-edge",
563+
"float-edge",
564+
"float-rle-size",
565+
"string-edge",
566+
"fractional-count",
567+
"float-count",
558568
],
559-
ids=["fractional-edge", "string-edge", "fractional-count"],
560569
)
561570
def test_rle_expand_rejects_non_int(rle_input: list[Any], match: str) -> None:
562-
"""expand_rle reads integral numbers only."""
571+
"""expand_rle reads integers only, not floats."""
563572
with pytest.raises(TypeError, match=match):
564573
expand_rle(rle_input)
565574

0 commit comments

Comments
 (0)