Skip to content

Commit 24fb05c

Browse files
committed
fix(metadata): read a legacy v2 zero chunk edge on an empty axis as 1
zarr-python 2.18.7 writes `chunks: [0]` for `zarr.zeros((0,), chunks=False)` and for `chunks=(0,)`, so stores with that document exist. Rejecting them at open would turn a previously-readable array into an error; leaving the 0 in place read uninitialised memory after a resize. Normalize the edge to 1 with a ZarrUserWarning instead — the same grid every other "one chunk spans the axis" spelling produces — and keep rejecting a zero edge on an axis that has data. Assisted-by: ClaudeCode:claude-fable-5-1
1 parent 4dde5bf commit 24fb05c

3 files changed

Lines changed: 44 additions & 12 deletions

File tree

‎changes/0000.bugfix.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
Zero-length dimensions are now handled by a single rule instead of a per-spelling patch: a chunk edge length is always at least 1, while a dimension's extent may be 0 (such a dimension simply has zero chunks). Every way of asking for "one chunk covering the axis" — `chunks=-1`, `chunks=False`, `chunks="auto"`, and `shards="auto"` — now derives the chunk size from the same helper, so they agree on chunk size 1 for a zero-length axis in both Zarr formats. Zarr format 2 metadata now rejects a chunk edge length of 0 with a clear error, matching Zarr format 3, instead of reading uninitialised data after a resize. Rectilinear chunk grids (`chunks=[[...], ...]`) can now be created on a zero-length dimension: since no list of positive edge lengths can sum to 0, the given edge lengths are stored as-is and describe the chunks the dimension will grow into on `append` or `resize`, exactly the state a rectilinear dimension is in after being resized down to 0. The private `FixedDimension(size=0, ...)` model, which previously carried its own zero-size special cases, now raises `ValueError`.
1+
Zero-length dimensions are now handled by a single rule instead of a per-spelling patch: a chunk edge length is always at least 1, while a dimension's extent may be 0 (such a dimension simply has zero chunks). Every way of asking for "one chunk covering the axis" — `chunks=-1`, `chunks=False`, `chunks="auto"`, and `shards="auto"` — now derives the chunk size from the same helper, so they agree on chunk size 1 for a zero-length axis in both Zarr formats. Zarr format 2 metadata now applies the same rule: a stored chunk edge length of 0 on a zero-length axis — which zarr-python 2.x wrote for `chunks=False` and `chunks=(0,)` — is read as 1 (with a `ZarrUserWarning`) so those stores stay readable and no longer read uninitialised data after a resize, while a chunk edge of 0 on an axis that has data is rejected with a clear error. Rectilinear chunk grids (`chunks=[[...], ...]`) can now be created on a zero-length dimension: since no list of positive edge lengths can sum to 0, the given edge lengths are stored as-is and describe the chunks the dimension will grow into on `append` or `resize`, exactly the state a rectilinear dimension is in after being resized down to 0. The private `FixedDimension(size=0, ...)` model, which previously carried its own zero-size special cases, now raises `ValueError`.

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

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,12 +90,26 @@ def __init__(
9090
shape_parsed = parse_shapelike(shape)
9191
chunks_parsed = parse_shapelike(chunks)
9292
# Same invariant as the Zarr format 3 chunk grid metadata: every chunk edge
93-
# length is at least 1, even on a zero-length axis.
94-
for dim_idx, chunk in enumerate(chunks_parsed):
93+
# length is at least 1. zarr-python 2.x wrote `chunks: [0]` for a zero-length
94+
# axis created with `chunks=False` or `chunks=(0,)`. Such an axis holds no
95+
# chunks, so those documents are readable; the edge is normalized to 1 so a
96+
# later resize does not divide by zero. On an axis that has data, 0 is invalid.
97+
normalized_chunks: list[int] = []
98+
for dim_idx, (extent, chunk) in enumerate(zip(shape_parsed, chunks_parsed, strict=False)):
9599
if chunk < 1:
96-
raise ValueError(
97-
f"Dimension {dim_idx}: chunk edge length must be >= 1, got {chunk}"
100+
if chunk < 0 or extent != 0:
101+
raise ValueError(
102+
f"Dimension {dim_idx}: chunk edge length must be >= 1, got {chunk}"
103+
)
104+
warnings.warn(
105+
f"Dimension {dim_idx}: chunk edge length 0 on a zero-length axis "
106+
"(as written by zarr-python 2.x) is treated as 1.",
107+
ZarrUserWarning,
108+
stacklevel=2,
98109
)
110+
chunk = 1
111+
normalized_chunks.append(chunk)
112+
chunks_parsed = tuple(normalized_chunks) + chunks_parsed[len(shape_parsed) :]
99113
compressor_parsed = parse_compressor(compressor)
100114
order_parsed = parse_indexing_order(order)
101115
dimension_separator_parsed = parse_separator(dimension_separator)

‎tests/test_metadata/test_v2.py‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -309,15 +309,33 @@ def test_from_dict_extra_fields() -> None:
309309
assert result == expected
310310

311311

312-
@pytest.mark.parametrize(("shape", "chunks"), [((0,), (0,)), ((4, 0), (4, 0)), ((5,), (0,))])
313-
def test_zero_chunk_edge_rejected(shape: tuple[int, ...], chunks: tuple[int, ...]) -> None:
314-
"""A chunk edge length of 0 is invalid metadata, whatever the array shape.
312+
@pytest.mark.parametrize(
313+
("shape", "chunks", "expected"),
314+
[((0,), (0,), (1,)), ((4, 0), (4, 0), (4, 1)), ((0, 0), (0, 0), (1, 1))],
315+
)
316+
def test_zero_chunk_edge_on_empty_axis_normalized(
317+
shape: tuple[int, ...], chunks: tuple[int, ...], expected: tuple[int, ...]
318+
) -> None:
319+
"""A stored chunk edge of 0 on a zero-length axis is read as 1, with a warning.
315320
316-
Older releases could write `chunks: [0]` for a zero-length axis; such documents read
317-
uninitialised memory once resized. The v2 layer now enforces the same `>= 1` rule as
318-
the Zarr format 3 chunk grid.
321+
zarr-python 2.x wrote `chunks: [0]` for such an axis (`chunks=False` or
322+
`chunks=(0,)`), and those documents must stay readable. Left at 0, a later resize
323+
read uninitialised memory; normalizing to 1 gives the axis the same grid every other
324+
"one chunk spans the axis" spelling produces.
319325
"""
320-
with pytest.raises(ValueError, match="chunk edge length must be >= 1, got 0"):
326+
with pytest.warns(ZarrUserWarning, match="chunk edge length 0 on a zero-length axis"):
327+
meta = ArrayV2Metadata(
328+
shape=shape, dtype=Float64(), chunks=chunks, fill_value=0.0, order="C"
329+
)
330+
assert meta.chunks == expected
331+
332+
333+
@pytest.mark.parametrize(("shape", "chunks"), [((5,), (0,)), ((4, 3), (4, 0))])
334+
def test_zero_chunk_edge_with_data_rejected(
335+
shape: tuple[int, ...], chunks: tuple[int, ...]
336+
) -> None:
337+
"""A chunk edge of 0 on an axis that has data is invalid metadata."""
338+
with pytest.raises(ValueError, match="chunk edge length must be >= 1"):
321339
ArrayV2Metadata(shape=shape, dtype=Float64(), chunks=chunks, fill_value=0.0, order="C")
322340

323341

0 commit comments

Comments
 (0)