Skip to content

Commit 632ac2b

Browse files
d-v-bclaude
andcommitted
fix(metadata): keep accepting the chunk sizes zarr 3.4.0 accepted in metadata constructors (patch release)
Nothing in a patch release may reject a chunk size that zarr 3.4.0 accepted. The one chunk edge rule (`parse_chunk_edge`, which also reads RLE repeat counts) now reads any integral number as the `int` it equals: an `int`, a `bool`, a NumPy integer or an integral float, so rectilinear grids written with float edges (`[[4.0, 2]]`) read again and the grid constructors accept NumPy integers; a fractional float is still rejected. A regular chunk shape may again be any iterable. `ArrayV2Metadata(chunks=...)` and `ShardingCodec(chunk_shape=...)` read their chunk shape with `parse_shapelike`, as in 3.4.0: a scalar, NumPy integers, bools and 0 are accepted, and a 0 is written back as given (the kerchunk writer in VirtualiZarr relies on `chunks=(0,)` for empty inlined arrays). Stored documents with a chunk size of 0 are still read by the upgrades. The strict rule returns in the next minor release. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9e29333 commit 632ac2b

6 files changed

Lines changed: 136 additions & 65 deletions

File tree

‎src/zarr/codecs/sharding.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,9 @@
4545
merge_and_encode_chunk,
4646
)
4747
from zarr.core.common import (
48-
parse_chunk_shape,
48+
ShapeLike,
4949
parse_named_configuration,
50+
parse_shapelike,
5051
product,
5152
)
5253
from zarr.core.config import config as zarr_config
@@ -458,13 +459,13 @@ class ShardingCodec(
458459
def __init__(
459460
self,
460461
*,
461-
chunk_shape: tuple[int, ...] | list[int],
462+
chunk_shape: ShapeLike,
462463
codecs: Iterable[Codec | dict[str, JSON]] = (BytesCodec(),),
463464
index_codecs: Iterable[Codec | dict[str, JSON]] = (BytesCodec(), Crc32cCodec()),
464465
index_location: ShardingCodecIndexLocation | IndexLocation = "end",
465466
subchunk_write_order: SubchunkWriteOrder = "morton",
466467
) -> None:
467-
chunk_shape_parsed = parse_chunk_shape(chunk_shape)
468+
chunk_shape_parsed = parse_shapelike(chunk_shape)
468469
codecs_parsed = parse_codecs(codecs)
469470
index_codecs_parsed = parse_codecs(index_codecs)
470471
_check_index_codecs_fixed_size(index_codecs_parsed)
@@ -503,7 +504,7 @@ def __getstate__(self) -> dict[str, Any]:
503504

504505
def __setstate__(self, state: dict[str, Any]) -> None:
505506
config = state["configuration"]
506-
object.__setattr__(self, "chunk_shape", parse_chunk_shape(config["chunk_shape"]))
507+
object.__setattr__(self, "chunk_shape", parse_shapelike(config["chunk_shape"]))
507508
object.__setattr__(self, "codecs", parse_codecs(config["codecs"]))
508509
object.__setattr__(self, "index_codecs", parse_codecs(config["index_codecs"]))
509510
object.__setattr__(self, "index_location", _parse_index_location(config["index_location"]))

‎src/zarr/core/common.py‎

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

33
import asyncio
44
import math
5+
import numbers
56
import warnings
67
from collections.abc import Iterable, Mapping, Sequence
78
from enum import Enum
@@ -282,16 +283,24 @@ def _subject(name: str, axis: int | None) -> str:
282283

283284

284285
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."""
285288
subject = _subject(name, axis)
286-
if isinstance(value, bool) or not isinstance(value, int):
287-
raise TypeError(f"{subject} must be an int, got {value!r}")
288-
if value < 1:
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}")
296+
if parsed < 1:
289297
raise ValueError(f"{subject} must be >= 1, got {value!r}")
290-
return value
298+
return parsed
291299

292300

293301
def parse_chunk_edge(size: object, axis: int | None = None) -> int:
294-
"""Check that `size` is a chunk edge length: an `int` (not a `bool`) of at least 1.
302+
"""Check that `size` is a chunk edge length: an integral number of at least 1, read
303+
as an `int`.
295304
296305
This is the one rule for chunk edge lengths in metadata: bare chunk sizes, explicit
297306
edges and run-length encoded sizes. `axis`, when given, is named in the error.
@@ -300,12 +309,12 @@ def parse_chunk_edge(size: object, axis: int | None = None) -> int:
300309

301310

302311
def parse_chunk_shape(data: object) -> tuple[int, ...]:
303-
"""Check a regular chunk shape: a list or tuple of one chunk edge length per axis
312+
"""Check a regular chunk shape: an iterable of one chunk edge length per axis
304313
(see `parse_chunk_edge`)."""
305314
match data:
306-
case list() | tuple():
315+
case Iterable():
307316
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}")
317+
raise TypeError(f"A chunk shape must be an iterable of chunk edge lengths, got {data!r}")
309318

310319

311320
def expand_rle(data: Sequence[object], axis: int | None = None) -> list[int]:

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Upgrades that read invalid stored array metadata documents written by older software.
22
33
This is the only place invalid metadata is read leniently; the metadata constructors
4-
are strict. An upgrade maps a stored array metadata document (parsed JSON) to a valid
4+
never reinterpret a chunk size. An upgrade maps a stored array metadata document (parsed JSON) to a valid
55
one and says how it read the document. `ArrayV2Metadata.from_dict` and
66
`ArrayV3Metadata.from_dict` apply the upgrades for their Zarr format, so every path
77
that parses a stored document, including consolidated metadata, goes through them, and

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
ZARRAY_JSON,
3939
ZATTRS_JSON,
4040
MemoryOrder,
41-
parse_chunk_shape,
41+
ShapeLike,
4242
parse_shapelike,
4343
)
4444
from zarr.core.config import config, parse_indexing_order
@@ -329,9 +329,10 @@ def parse_compressor(data: object) -> Numcodec | None:
329329
raise ValueError(msg)
330330

331331

332-
def parse_chunks(chunks: object, shape: tuple[int, ...]) -> tuple[int, ...]:
333-
"""Check a chunk shape: one chunk edge length (an `int` >= 1) per array axis."""
334-
chunks_parsed = parse_chunk_shape(chunks)
332+
def parse_chunks(chunks: ShapeLike, shape: tuple[int, ...]) -> tuple[int, ...]:
333+
"""Check a chunk shape: one non-negative integer per array axis (see
334+
`parse_shapelike`). Stored chunk sizes of 0 are read by `zarr.core.metadata.upgrades`."""
335+
chunks_parsed = parse_shapelike(chunks)
335336
if len(chunks_parsed) != len(shape):
336337
raise ValueError(
337338
f"The `shape` and `chunks` attributes must have the same length. "

‎tests/test_metadata/test_upgrades.py‎

Lines changed: 99 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ def _read_strictly(doc: dict[str, JSON]) -> ArrayV2Metadata | ArrayV3Metadata:
221221

222222
def test_stored_negative_chunk_size_rejected() -> None:
223223
"""No known writer stored a negative chunk size: it is rejected, not upgraded."""
224-
with pytest.raises(ValueError, match="^Dimension 0: chunk edge length must be >= 1, got -1$"):
224+
with pytest.raises(ValueError, match="^Expected all values to be non-negative"):
225225
_read_strictly(_v2_doc([4], [-1]))
226226

227227

@@ -232,19 +232,12 @@ def test_stored_chunk_shape_ndim_mismatch_rejected() -> None:
232232
_read_strictly(_v3_doc([4, 4], [0]))
233233

234234

235-
def test_stored_float_chunk_size_rejected() -> None:
236-
"""No known writer stored a float chunk size: it is rejected, not upgraded."""
235+
def test_stored_fractional_chunk_size_rejected() -> None:
236+
"""A stored chunk size that is not an integral number is rejected, not upgraded."""
237237
with pytest.raises(
238-
TypeError, match=r"^Dimension 0: chunk edge length must be an int, got 4\.0$"
238+
TypeError, match=r"^Dimension 0: chunk edge length must be an integer, got 4\.5$"
239239
):
240-
_read_strictly(_v3_doc([4], [4.0]))
241-
242-
243-
def test_stored_zero_inner_chunk_size_rejected() -> None:
244-
"""No known writer stored an inner chunk size of 0, and no span defines one: it is
245-
rejected, not upgraded."""
246-
with pytest.raises(ValueError, match="^Dimension 0: chunk edge length must be >= 1, got 0$"):
247-
_read_strictly(_v3_doc([4], [0], inner=[0]))
240+
_read_strictly(_v3_doc([4], [4.5]))
248241

249242

250243
def test_v2_constructor_rejects_chunks_of_wrong_length() -> None:
@@ -271,33 +264,52 @@ def _rectilinear_from_dict(chunk_shapes: list[Any]) -> RectilinearChunkGridMetad
271264
)
272265

273266

267+
def _second_edge(grid: RectilinearChunkGridMetadata) -> int:
268+
edges = grid.chunk_shapes[0]
269+
assert isinstance(edges, tuple)
270+
return edges[1]
271+
272+
274273
CHUNK_EDGE_SITES: dict[str, Callable[[Any], object]] = {
275-
"regular": lambda size: RegularChunkGridMetadata(chunk_shape=(size,)),
276-
"v2": lambda size: _v2_metadata((size,)),
277-
"rectilinear-bare": lambda size: _rectilinear((size,)),
278-
"rectilinear-edge": lambda size: _rectilinear(((4, size),)),
279-
"rectilinear-bare-json": lambda size: _rectilinear_from_dict([size]),
280-
"rectilinear-edge-json": lambda size: _rectilinear_from_dict([[4, size]]),
281-
"rectilinear-rle-json": lambda size: _rectilinear_from_dict([[[size, 2]]]),
282-
"sharding-inner": lambda size: ShardingCodec(chunk_shape=(size,)),
274+
"regular": lambda size: RegularChunkGridMetadata(chunk_shape=(size,)).chunk_shape[0],
275+
"rectilinear-bare": lambda size: _rectilinear((size,)).chunk_shapes[0],
276+
"rectilinear-edge": lambda size: _second_edge(_rectilinear(((4, size),))),
277+
"rectilinear-bare-json": lambda size: _rectilinear_from_dict([size]).chunk_shapes[0],
278+
"rectilinear-edge-json": lambda size: _second_edge(_rectilinear_from_dict([[4, size]])),
279+
"rectilinear-rle-json": lambda size: _second_edge(_rectilinear_from_dict([[[size, 2]]])),
283280
}
281+
"""Each place chunk grid metadata reads a chunk edge length, returning the edge it read."""
284282

285283

286284
@pytest.mark.parametrize("site", CHUNK_EDGE_SITES)
287-
@pytest.mark.parametrize("size", [True, False, 4.0, np.int64(4), "4"])
288-
def test_metadata_rejects_non_int_chunk_edge(site: str, size: object) -> None:
289-
"""Metadata built in code takes chunk edge lengths as `int`s only, everywhere."""
285+
@pytest.mark.parametrize(
286+
("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"],
289+
)
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."""
293+
edge = CHUNK_EDGE_SITES[site](size)
294+
assert type(edge) is int
295+
assert edge == expected
296+
297+
298+
@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:
290301
with pytest.raises(
291-
TypeError, match=re.escape(f"Dimension 0: chunk edge length must be an int, got {size!r}")
302+
TypeError,
303+
match=re.escape(f"Dimension 0: chunk edge length must be an integer, got {size!r}"),
292304
):
293305
CHUNK_EDGE_SITES[site](size)
294306

295307

296308
@pytest.mark.parametrize("site", CHUNK_EDGE_SITES)
297-
@pytest.mark.parametrize("size", [0, -1])
309+
@pytest.mark.parametrize("size", [0, False, -1])
298310
def test_metadata_rejects_chunk_edge_below_one(site: str, size: int) -> None:
299-
"""Metadata built in code is strict: a chunk edge length below 1 is rejected,
300-
without a warning."""
311+
"""Chunk grid metadata built in code is strict: a chunk edge length below 1 is
312+
rejected, without a warning."""
301313
with warnings.catch_warnings():
302314
warnings.simplefilter("error", ZarrUserWarning)
303315
with pytest.raises(
@@ -306,25 +318,71 @@ def test_metadata_rejects_chunk_edge_below_one(site: str, size: int) -> None:
306318
CHUNK_EDGE_SITES[site](size)
307319

308320

309-
CHUNK_SHAPE_SITES: dict[str, Callable[[Any], object]] = {
310-
"regular": lambda chunk_shape: RegularChunkGridMetadata(chunk_shape=chunk_shape),
311-
"v2": _v2_metadata,
312-
"sharding-inner": lambda chunk_shape: ShardingCodec(chunk_shape=chunk_shape),
313-
}
314-
315-
316-
@pytest.mark.parametrize("site", CHUNK_SHAPE_SITES)
317-
@pytest.mark.parametrize("chunk_shape", [4, np.int64(4), "10", {"a": 1}, range(1, 2)])
318-
def test_metadata_rejects_chunk_shape_not_list_or_tuple(site: str, chunk_shape: object) -> None:
319-
"""A regular chunk shape is a list or tuple; anything else is rejected as a whole,
320-
not iterated as if its elements were chunk edge lengths."""
321+
@pytest.mark.parametrize("chunk_shape", [4, np.int64(4), None])
322+
def test_regular_chunk_grid_rejects_chunk_shape_not_iterable(chunk_shape: Any) -> None:
321323
with pytest.raises(
322324
TypeError,
323325
match=re.escape(
324-
f"A chunk shape must be a list or tuple of chunk edge lengths, got {chunk_shape!r}"
326+
f"A chunk shape must be an iterable of chunk edge lengths, got {chunk_shape!r}"
325327
),
326328
):
327-
CHUNK_SHAPE_SITES[site](chunk_shape)
329+
RegularChunkGridMetadata(chunk_shape=chunk_shape)
330+
331+
332+
def _sharding_chunk_shape(chunks: Any) -> tuple[tuple[int, ...], object]:
333+
codec = ShardingCodec(chunk_shape=chunks)
334+
configuration = cast("dict[str, JSON]", codec.to_dict()["configuration"])
335+
return codec.chunk_shape, configuration["chunk_shape"]
336+
337+
338+
CHUNK_SHAPE_SITES: dict[str, Callable[[Any], tuple[tuple[int, ...], object]]] = {
339+
"v2": lambda chunks: ((md := _v2_metadata(chunks)).chunks, md.to_dict()["chunks"]),
340+
"sharding-inner": _sharding_chunk_shape,
341+
}
342+
"""`ArrayV2Metadata` and `ShardingCodec` read a chunk shape as an array shape, returning
343+
the chunk shape and the value `to_dict` writes for it."""
344+
345+
346+
@pytest.mark.parametrize("site", CHUNK_SHAPE_SITES)
347+
@pytest.mark.parametrize(
348+
("chunks", "expected"),
349+
[
350+
((4,), (4,)),
351+
([4], (4,)),
352+
(4, (4,)),
353+
(np.int64(4), (4,)),
354+
((np.int64(4),), (4,)),
355+
(np.array([4]), (4,)),
356+
((True,), (1,)),
357+
((0,), (0,)),
358+
((False,), (0,)),
359+
(range(4, 5), (4,)),
360+
],
361+
)
362+
def test_chunk_shape_read_as_array_shape(
363+
site: str, chunks: object, expected: tuple[int, ...]
364+
) -> None:
365+
"""`ArrayV2Metadata` and `ShardingCodec` read their chunk shape as `parse_shapelike`
366+
reads an array shape: an integer or an iterable of non-negative integers, including
367+
NumPy integers and bools. A chunk size of 0 is written back as given; reading a
368+
stored 0 is `zarr.core.metadata.upgrades`' business."""
369+
parsed, written = CHUNK_SHAPE_SITES[site](chunks)
370+
assert parsed == expected
371+
assert all(type(size) is int for size in parsed)
372+
assert written == expected
373+
374+
375+
@pytest.mark.parametrize("site", CHUNK_SHAPE_SITES)
376+
def test_chunk_shape_read_as_array_shape_rejects_negative(site: str) -> None:
377+
with pytest.raises(ValueError, match="Expected all values to be non-negative"):
378+
CHUNK_SHAPE_SITES[site]((-1,))
379+
380+
381+
@pytest.mark.parametrize("site", CHUNK_SHAPE_SITES)
382+
@pytest.mark.parametrize("chunks", [(4.0,), "4", None])
383+
def test_chunk_shape_read_as_array_shape_rejects_non_integer(site: str, chunks: object) -> None:
384+
with pytest.raises(TypeError, match="Expected an"):
385+
CHUNK_SHAPE_SITES[site](chunks)
328386

329387

330388
def _rewrite_doc(path: Path, zarr_format: Literal[2, 3], edit: Any) -> None:

‎tests/test_unified_chunk_grid.py‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,8 @@ 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]),
498+
([[True, 2], [np.int64(3), np.int64(1)]], [1, 1, 3]),
497499
],
498500
)
499501
def test_rle_expand(compressed: list[Any], expected: list[int]) -> None:
@@ -550,14 +552,14 @@ def test_rle_expand_rejects_invalid(rle_input: list[Any], match: str) -> None:
550552
@pytest.mark.parametrize(
551553
("rle_input", "match"),
552554
[
553-
([10.0], "Chunk edge length must be an int, got 10.0"),
554-
([True], "Chunk edge length must be an int, got True"),
555-
([[10, 3.0]], "RLE repeat count must be an int, got 3.0"),
555+
([10.5], "Chunk edge length must be an integer, got 10.5"),
556+
(["10"], "Chunk edge length must be an integer, got '10'"),
557+
([[10, 3.5]], "RLE repeat count must be an integer, got 3.5"),
556558
],
557-
ids=["float-edge", "bool-edge", "float-count"],
559+
ids=["fractional-edge", "string-edge", "fractional-count"],
558560
)
559561
def test_rle_expand_rejects_non_int(rle_input: list[Any], match: str) -> None:
560-
"""expand_rle takes JSON integers only: no stored document holds integral floats."""
562+
"""expand_rle reads integral numbers only."""
561563
with pytest.raises(TypeError, match=match):
562564
expand_rle(rle_input)
563565

@@ -566,11 +568,11 @@ def test_rle_expand_rejects_non_int(rle_input: list[Any], match: str) -> None:
566568
("rle_input", "match"),
567569
[
568570
([0], "chunk edge length must be >= 1"),
569-
([10.0], "chunk edge length must be an int"),
571+
([10.5], "chunk edge length must be an integer"),
570572
([[5, 0]], "RLE repeat count must be >= 1"),
571573
([[5, 2, 1]], r"RLE entries must be an integer or \[size, count\]"),
572574
],
573-
ids=["zero-edge", "float-edge", "zero-rle-count", "rle-entry-of-three"],
575+
ids=["zero-edge", "fractional-edge", "zero-rle-count", "rle-entry-of-three"],
574576
)
575577
def test_rle_expand_names_dimension(rle_input: list[Any], match: str) -> None:
576578
"""Given the dimension `axis` the edges belong to, every error of expand_rle names it."""

0 commit comments

Comments
 (0)