Skip to content

Commit c1353bf

Browse files
d-v-bclaude
andcommitted
refactor(metadata): one rule for bare sizes and edge lists; one noun in messages
- `_validate_chunk_shapes` decides "edge list or bare size" with one `match`: a list or tuple is an edge list, anything else is a bare size checked by `parse_chunk_edge`, so a string dimension such as `"10"` is rejected as not an int instead of being iterated per character. Stored rectilinear `from_dict` makes the same JSON split and passes the dimension to `expand_rle`, so an invalid edge or RLE count inside a list names its dimension. - Messages say "dimension" throughout, lowercase after the colon ("Dimension 0: chunk edge length must be >= 1, got 0"); the upgrade warnings read "0 in dimension 0 as one chunk spanning the dimension". - The upgrades test for JSON arrays with `list` only (a stored document holds no tuples), and `_read_chunk_size` says what `span=None` means. - `ArrayV2Metadata.from_dict` copies the document once. - The rejected stored chunk shapes get one test per error case. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 121b6b2 commit c1353bf

5 files changed

Lines changed: 85 additions & 55 deletions

File tree

‎src/zarr/core/common.py‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -276,11 +276,12 @@ def _default_zarr_format() -> ZarrFormat:
276276
return cast("ZarrFormat", int(zarr_config.get("default_zarr_format", 3)))
277277

278278

279-
def _parse_positive_int(value: object, name: str) -> int:
279+
def _parse_positive_int(value: object, name: str, axis: int | None) -> int:
280+
subject = name[0].upper() + name[1:] if axis is None else f"Dimension {axis}: {name}"
280281
if isinstance(value, bool) or not isinstance(value, int):
281-
raise TypeError(f"{name} must be an int, got {value!r}")
282+
raise TypeError(f"{subject} must be an int, got {value!r}")
282283
if value < 1:
283-
raise ValueError(f"{name} must be >= 1, got {value!r}")
284+
raise ValueError(f"{subject} must be >= 1, got {value!r}")
284285
return value
285286

286287

@@ -290,8 +291,7 @@ def parse_chunk_edge(size: object, axis: int | None = None) -> int:
290291
This is the one rule for chunk edge lengths in metadata: bare chunk sizes, explicit
291292
edges and run-length encoded sizes. `axis`, when given, is named in the error.
292293
"""
293-
where = "" if axis is None else f"Dimension {axis}: "
294-
return _parse_positive_int(size, f"{where}Chunk edge length")
294+
return _parse_positive_int(size, "chunk edge length", axis)
295295

296296

297297
def parse_chunk_shape(data: object) -> tuple[int, ...]:
@@ -301,8 +301,9 @@ def parse_chunk_shape(data: object) -> tuple[int, ...]:
301301
return tuple(parse_chunk_edge(size, axis) for axis, size in enumerate(data))
302302

303303

304-
def expand_rle(data: Sequence[object]) -> list[int]:
305-
"""Expand a mixed array of bare integers and RLE pairs.
304+
def expand_rle(data: Sequence[object], axis: int | None = None) -> list[int]:
305+
"""Expand a mixed array of bare integers and RLE pairs, the edges of dimension
306+
`axis` (named in errors, when given).
306307
307308
Per the rectilinear chunk grid spec, each element can be:
308309
- a bare integer (an explicit edge length)
@@ -314,9 +315,10 @@ def expand_rle(data: Sequence[object]) -> list[int]:
314315
if len(item) != 2:
315316
raise ValueError(f"RLE entries must be an integer or [size, count], got {item}")
316317
size, count = item
317-
result.extend([parse_chunk_edge(size)] * _parse_positive_int(count, "RLE repeat count"))
318+
repeat = _parse_positive_int(count, "RLE repeat count", axis)
319+
result.extend([parse_chunk_edge(size, axis)] * repeat)
318320
else:
319-
result.append(parse_chunk_edge(item))
321+
result.append(parse_chunk_edge(item, axis))
320322
return result
321323

322324

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

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,9 @@ def warn_readings(readings: Sequence[str], path: str | None) -> None:
4949
warnings.warn(f"{subject}{' '.join(readings)} {RESAVE_HINT}", ZarrUserWarning, stacklevel=2)
5050

5151

52-
def _is_int_list(value: object) -> TypeGuard[list[int] | tuple[int, ...]]:
52+
def _is_int_list(value: object) -> TypeGuard[list[int]]:
5353
"""Whether `value` is a JSON array of integers (JSON `false` and `true` count)."""
54-
return isinstance(value, list | tuple) and all(isinstance(v, int) for v in value)
54+
return isinstance(value, list) and all(isinstance(v, int) for v in value)
5555

5656

5757
def _read_chunk_size(size: JSON, span: int | None, unit: int) -> tuple[int, str | None] | None:
@@ -61,7 +61,8 @@ def _read_chunk_size(size: JSON, span: int | None, unit: int) -> tuple[int, str
6161
entry cannot be read, which leaves it for the metadata constructors to reject. A
6262
JSON int >= 1 is kept, JSON `true` is read as 1, and 0 or JSON `false` is read as
6363
one chunk spanning the axis of length `span`, a multiple of `unit` (the inner chunk
64-
size of a shard), when the span is known.
64+
size of a shard). `span` is `None` where no stored 0 is known, as in the inner
65+
chunk shape of a sharding codec: 0 is then left for the constructors to reject.
6566
"""
6667
match size:
6768
case True:
@@ -70,7 +71,7 @@ def _read_chunk_size(size: JSON, span: int | None, unit: int) -> tuple[int, str
7071
return size, None
7172
case int() if size == 0 and span is not None:
7273
edge = full_span_chunk_size(span, unit)
73-
how = f"one chunk spanning the axis ({edge})"
74+
how = f"one chunk spanning the dimension ({edge})"
7475
if span > 0:
7576
how += (
7677
", and as no chunk can be stored under a chunk size of 0, the array "
@@ -89,7 +90,7 @@ def _read_chunk_shape(
8990
Returns the chunk shape and, if an entry is invalid, a sentence saying how the
9091
`name` was read; `None` if it cannot be read.
9192
"""
92-
if not (isinstance(stored, list | tuple) and len(stored) == len(spans)):
93+
if not (isinstance(stored, list) and len(stored) == len(spans)):
9394
return None
9495
edges: list[int] = []
9596
readings: list[str] = []
@@ -101,7 +102,7 @@ def _read_chunk_shape(
101102
edge, how = read
102103
edges.append(edge)
103104
if how is not None:
104-
readings.append(f"{json.dumps(size)} on axis {axis} as {how}")
105+
readings.append(f"{json.dumps(size)} in dimension {axis} as {how}")
105106
if not readings:
106107
return edges, None
107108
return edges, (
@@ -124,7 +125,7 @@ def _sharding_codec(doc: ArrayDocument) -> tuple[Sequence[JSON], int, Mapping[st
124125
"""The codec list of a Zarr format 3 array document, with the position and the
125126
configuration of its sharding codec, if it has one."""
126127
codecs = doc.get("codecs")
127-
if isinstance(codecs, list | tuple):
128+
if isinstance(codecs, list):
128129
for index, codec in enumerate(codecs):
129130
if isinstance(codec, Mapping) and codec.get("name") == "sharding_indexed":
130131
configuration = codec.get("configuration")

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -155,16 +155,16 @@ def from_dict(cls, data: dict[str, Any], *, path: str | None = None) -> ArrayV2M
155155
"""Read a stored `.zarray` document (with its attributes). An invalid document
156156
that `zarr.core.metadata.upgrades` can read warns, naming the array at `path`."""
157157
upgraded, readings = upgrade_array_document(data, V2_ARRAY_UPGRADES)
158-
data = dict(upgraded)
159-
_data = data.copy()
158+
# a new dict, because we are modifying it
159+
_data: dict[str, Any] = dict(upgraded)
160160
# Check that the zarr_format attribute is correct.
161161
_ = parse_zarr_format(_data.pop("zarr_format"))
162162

163163
# To resolve a numpy object dtype array, we need to search for an object codec,
164164
# which could be in filters or as a compressor.
165165
# we will reference a hard-coded collection of object codec ids for this search.
166166

167-
_filters, _compressor = (data.get("filters"), data.get("compressor"))
167+
_filters, _compressor = (_data.get("filters"), _data.get("compressor"))
168168
if _filters is not None:
169169
_filters = cast("tuple[dict[str, JSON], ...]", _filters)
170170
object_codec_id = get_object_codec_id(tuple(_filters) + (_compressor,))
@@ -173,7 +173,7 @@ def from_dict(cls, data: dict[str, Any], *, path: str | None = None) -> ArrayV2M
173173
# we add a layer of indirection here around the dtype attribute of the array metadata
174174
# because we also need to know the object codec id, if any, to resolve the data type
175175
dtype_spec: DTypeSpec_V2 = {
176-
"name": data["dtype"],
176+
"name": _data["dtype"],
177177
"object_codec_id": object_codec_id,
178178
}
179179
dtype = get_data_type_from_json(dtype_spec, zarr_format=2)

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

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -239,13 +239,14 @@ def _validate_chunk_shapes(
239239
"""
240240
result: list[int | tuple[int, ...]] = []
241241
for dim_idx, dim_spec in enumerate(chunk_shapes):
242-
if isinstance(dim_spec, Iterable):
243-
edges = tuple(parse_chunk_edge(edge, dim_idx) for edge in dim_spec)
244-
if not edges:
245-
raise ValueError(f"Dimension {dim_idx} has no chunk edges.")
246-
result.append(edges)
247-
else:
248-
result.append(parse_chunk_edge(dim_spec, dim_idx))
242+
match dim_spec:
243+
case list() | tuple():
244+
edges = tuple(parse_chunk_edge(edge, dim_idx) for edge in dim_spec)
245+
if not edges:
246+
raise ValueError(f"Dimension {dim_idx} has no chunk edges.")
247+
result.append(edges)
248+
case _:
249+
result.append(parse_chunk_edge(dim_spec, dim_idx))
249250
return tuple(result)
250251

251252

@@ -363,8 +364,8 @@ def from_dict(cls, data: RectilinearChunkGridMetadataJSON) -> Self: # type: ign
363364
validate_rectilinear_kind(configuration.get("kind"))
364365
raw_shapes = configuration["chunk_shapes"]
365366
parsed = [
366-
tuple(expand_rle(dim_spec)) if isinstance(dim_spec, list) else dim_spec
367-
for dim_spec in raw_shapes
367+
tuple(expand_rle(dim_spec, axis)) if isinstance(dim_spec, list) else dim_spec
368+
for axis, dim_spec in enumerate(raw_shapes)
368369
]
369370
return cls(chunk_shapes=tuple(parsed))
370371

‎tests/test_metadata/test_upgrades.py‎

Lines changed: 52 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -100,32 +100,40 @@ def _chunk_shapes(metadata: ArrayV2Metadata | ArrayV3Metadata) -> tuple[Any, Any
100100
(
101101
_v2_doc([0, 4], [0, 4]),
102102
((1, 4), None),
103-
r"0 on axis 0 as one chunk spanning the axis \(1\)\.",
103+
r"0 in dimension 0 as one chunk spanning the dimension \(1\)\.",
104104
),
105105
(
106106
_v3_doc([0], [False]),
107107
((1,), None),
108-
r"false on axis 0 as one chunk spanning the axis \(1\)\.",
108+
r"false in dimension 0 as one chunk spanning the dimension \(1\)\.",
109109
),
110-
(_v2_doc([5], [True]), ((1,), None), "true on axis 0 as 1"),
110+
(_v2_doc([5], [True]), ((1,), None), "true in dimension 0 as 1"),
111111
(
112112
_v3_doc([5, 4], [True, 4]),
113113
((1, 4), None),
114-
r"\[true, 4\] is invalid.*true on axis 0 as 1",
114+
r"\[true, 4\] is invalid.*true in dimension 0 as 1",
115115
),
116116
(
117117
_v2_doc([3], [0]),
118118
((3,), None),
119-
r"spanning the axis \(3\), and .* holds only its fill value",
119+
r"spanning the dimension \(3\), and .* holds only its fill value",
120120
),
121-
(_v3_doc([4, 3], [4, 0]), ((4, 3), None), "0 on axis 1 as .* holds only its fill value"),
122-
(_v3_doc([0], [0], inner=[4]), ((4,), (4,)), r"spanning the axis \(4\)\."),
121+
(
122+
_v3_doc([4, 3], [4, 0]),
123+
((4, 3), None),
124+
"0 in dimension 1 as .* holds only its fill value",
125+
),
126+
(_v3_doc([0], [0], inner=[4]), ((4,), (4,)), r"spanning the dimension \(4\)\."),
123127
(
124128
_v3_doc([10], [0], inner=[4]),
125129
((12,), (4,)),
126-
r"spanning the axis \(12\), and .* holds only its fill value",
130+
r"spanning the dimension \(12\), and .* holds only its fill value",
131+
),
132+
(
133+
_v3_doc([0, 3], [0, 3], inner=[2, 3]),
134+
((2, 3), (2, 3)),
135+
r"spanning the dimension \(2\)\.",
127136
),
128-
(_v3_doc([0, 3], [0, 3], inner=[2, 3]), ((2, 3), (2, 3)), r"spanning the axis \(2\)\."),
129137
(
130138
_v3_doc([5], [True], inner=[True]),
131139
((1,), (1,)),
@@ -203,24 +211,40 @@ def test_invalid_upgraded_document_raises_without_warning(doc: dict[str, JSON],
203211
metadata_cls.from_dict(doc)
204212

205213

206-
@pytest.mark.parametrize(
207-
("doc", "error"),
208-
[
209-
(_v2_doc([4], [-1]), "Dimension 0: Chunk edge length must be >= 1, got -1"),
210-
(_v3_doc([4, 4], [0]), "Dimension 0: Chunk edge length must be >= 1, got 0"),
211-
(_v3_doc([4], [4.0]), "Dimension 0: Chunk edge length must be an int, got 4.0"),
212-
(_v3_doc([4], [0], inner=[0]), "Dimension 0: Chunk edge length must be >= 1, got 0"),
213-
],
214-
ids=["negative", "ndim-mismatch", "float", "sharded-inner-zero"],
215-
)
216-
def test_stored_chunk_shape_not_upgraded(doc: dict[str, JSON], error: str) -> None:
217-
"""Invalid chunk sizes no known writer stored, and chunk shapes with the wrong
218-
number of axes, are not upgraded, only rejected."""
214+
def _read_strictly(doc: dict[str, JSON]) -> ArrayV2Metadata | ArrayV3Metadata:
215+
"""Read `doc`, failing on any warning that it was upgraded."""
219216
metadata_cls = ArrayV2Metadata if doc["zarr_format"] == 2 else ArrayV3Metadata
220217
with warnings.catch_warnings():
221218
warnings.simplefilter("error", ZarrUserWarning)
222-
with pytest.raises((TypeError, ValueError), match=re.escape(error)):
223-
metadata_cls.from_dict(doc)
219+
return metadata_cls.from_dict(doc)
220+
221+
222+
def test_stored_negative_chunk_size_rejected() -> None:
223+
"""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$"):
225+
_read_strictly(_v2_doc([4], [-1]))
226+
227+
228+
def test_stored_chunk_shape_ndim_mismatch_rejected() -> None:
229+
"""A chunk shape with the wrong number of dimensions is not upgraded, so its 0 is
230+
rejected."""
231+
with pytest.raises(ValueError, match="^Dimension 0: chunk edge length must be >= 1, got 0$"):
232+
_read_strictly(_v3_doc([4, 4], [0]))
233+
234+
235+
def test_stored_float_chunk_size_rejected() -> None:
236+
"""No known writer stored a float chunk size: it is rejected, not upgraded."""
237+
with pytest.raises(
238+
TypeError, match=r"^Dimension 0: chunk edge length must be an int, got 4\.0$"
239+
):
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]))
224248

225249

226250
def test_v2_constructor_rejects_chunks_of_wrong_length() -> None:
@@ -264,7 +288,7 @@ def _rectilinear_from_dict(chunk_shapes: list[Any]) -> RectilinearChunkGridMetad
264288
def test_metadata_rejects_non_int_chunk_edge(site: str, size: object) -> None:
265289
"""Metadata built in code takes chunk edge lengths as `int`s only, everywhere."""
266290
with pytest.raises(
267-
TypeError, match=re.escape(f"Chunk edge length must be an int, got {size!r}")
291+
TypeError, match=re.escape(f"Dimension 0: chunk edge length must be an int, got {size!r}")
268292
):
269293
CHUNK_EDGE_SITES[site](size)
270294

@@ -276,7 +300,9 @@ def test_metadata_rejects_chunk_edge_below_one(site: str, size: int) -> None:
276300
without a warning."""
277301
with warnings.catch_warnings():
278302
warnings.simplefilter("error", ZarrUserWarning)
279-
with pytest.raises(ValueError, match=f"Chunk edge length must be >= 1, got {size}"):
303+
with pytest.raises(
304+
ValueError, match=f"Dimension 0: chunk edge length must be >= 1, got {size}"
305+
):
280306
CHUNK_EDGE_SITES[site](size)
281307

282308

0 commit comments

Comments
 (0)