Skip to content

Commit 630bf36

Browse files
authored
feat(zarr-metadata): draw nested fields and codec pipelines (#4597)
* feat(zarr-metadata): draw nested fields and codec pipelines Add Hypothesis strategies for struct, cast_value and sharding_indexed, which draw the fields they hold from the same Strategies mapping, and a `pipelines` strategy that walks a codec pipeline, drawing each codec for the chunk the codec before it hands on via its definition's transition. A shard's inner and index pipelines are drawn for the chunks its definition's `pipelines` gives. Shards and structs nest at most one level deep, and strategies are wrapped in a mapping with a short repr so Hypothesis's error notes stay under its 30,000-character warning. Every strategy record's functions now take the Strategies mapping as their last argument. Assisted-by: ClaudeCode:claude-opus-5-5 * fix(zarr-metadata): reject non-numeric data types in arithmetic codecs `NOT_NUMBERS` predates the zarr-python data types, so `cast_value` and `scale_offset` accepted `fixed_length_utf32`, `null_terminated_bytes`, `raw_bytes` and `variable_length_bytes`, and the strategies drew them. The cast_value spec defines the codec only for floating-point and integral data types. Assisted-by: ClaudeCode:claude-opus-5-5 * fix(zarr-metadata): let the later of two same-named strategies win `_scope` documented this but raised `ScopeConflictError`, so `declarations` failed for any definition named as a default, which worked before this branch. Pipelines and data type names now draw only the definition that claims a name, and `declarations` reads a draw with its own definition claiming the name. Assisted-by: ClaudeCode:claude-opus-5-5 * test(zarr-metadata): check a same-named definition reads its own draws The test compared a draw with the bare name, which depended on the example Hypothesis returned and said nothing of which definition read it. Every spelling is now read by the definition it was drawn for. Assisted-by: ClaudeCode:claude-opus-5-5 * chore(zarr-metadata): number the nested strategies changelog fragments after #4597 Assisted-by: ClaudeCode:claude-opus-5-5 * fix(zarr-metadata): keep same-named definitions out of nested draws The struct and shard strategies removed the default definition by identity before drawing what they hold. A custom definition with the same name stayed in the inner strategies, so it could claim the name there and be drawn, and the default then refused the result with a ValueError. Filter by name instead. Assisted-by: ClaudeCode:claude-opus-5-5 * fix(zarr-metadata): draw long runs in rectilinear dimensions A run held at most 4 chunks, so the `[size, count]` spelling was never drawn for what it is for, and a long dimension was covered by a few small chunks and one huge one. Draw counts sized to the dimension, and always write a run too long to list as a pair. Reach tests now cover each spelling of a dimension, not only that a pair is drawn at all. Assisted-by: ClaudeCode:claude-opus-5-5 * fix(zarr-metadata): sample float fills, shard factors and struct fields evenly A measured audit found strategies that drew valid metadata from little of what they could. Hex float fills came from a small-biased integer, so 83% of float64 fills were subnormal and few were normal. Integer float fills stopped at the limit of the narrowest type. Rectilinear edges rarely shared a factor, so 70% of a shard's axes held inner chunks of length 1. A struct field's type was drawn after its name, which made the first data type about a fifth of all fields. Draw hex fills from floats, infinities and NaN payloads as well as raw bits, limit integers by width, draw edges with a common factor, and draw a field's type first. Divisor search is now bounded, so a very long shard no longer takes billions of steps. New tests measure shares at the number of examples a test runs, which plain reach tests do not see. Assisted-by: ClaudeCode:claude-opus-5-5 * fix(zarr-metadata): keep regular chunk lengths within a signed 64-bit size Axes can be up to 2**63 - 1 long, but regular and bare rectilinear chunk lengths reached twice that, which a reader indexing with int64 cannot hold. Cap them. A rectilinear last edge needs no cap: the runs before it cover at least one factor, so rounding up cannot pass the axis. Correct two docstrings, and require a covering run to count more than one chunk in its reach test, since the leftover edge passed it on its own. Assisted-by: ClaudeCode:claude-opus-5-5 * fix(zarr-metadata): draw non-finite and hex scale_offset values An offset and a scale are fill values of the chunk's data type, but the strategy drew only finite floats, and never an integer spelling. It now draws every spelling a fill value takes, and still never a scale of zero. Assisted-by: ClaudeCode:claude-opus-5-5
1 parent a981abf commit 630bf36

14 files changed

Lines changed: 1831 additions & 315 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
`cast_value` and `scale_offset` reject `fixed_length_utf32`, `null_terminated_bytes`, `raw_bytes` and `variable_length_bytes`, whose values are not numbers. The strategies no longer draw them for either codec. The `scale_offset` strategy now draws `offset` and `scale` in every spelling a fill value of the data type takes, including integers, `NaN`, the infinities and the hex strings of their bits; a scale is still never zero.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Added strategies to `zarr_metadata.testing.strategies` for the definitions that hold other declarations: `struct`, `cast_value` and `sharding_indexed`. Their nested declarations are drawn from the same `Strategies` mapping, so a struct's field types, a cast's target data type and a shard's codecs come from every definition the mapping holds. A new `pipelines` strategy draws a whole codec pipeline for a `Chunk`, drawing each codec for the chunk the codec before it hands on, as that codec's `transition` gives it. Shards are drawn at most one inside another, and structs likewise. Every function a strategy record holds now also takes the `Strategies` mapping as its last argument, and `declarations` reads what it draws in the scope of every definition the mapping holds.

‎packages/zarr-metadata/src/zarr_metadata/testing/_chunk_grid.py‎

Lines changed: 62 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -14,86 +14,122 @@
1414
from hypothesis import strategies as st
1515

1616
from zarr_metadata.testing._strategy import MAX_RANK, ChunkGridStrategy
17-
from zarr_metadata.v3.chunk_grid.rectilinear import RECTILINEAR_CHUNK_GRID
18-
from zarr_metadata.v3.chunk_grid.regular import REGULAR_CHUNK_GRID
17+
from zarr_metadata.v3.chunk_grid.rectilinear import (
18+
RECTILINEAR_CHUNK_GRID,
19+
RectilinearChunkGridConfiguration,
20+
RectilinearDimSpec,
21+
)
22+
from zarr_metadata.v3.chunk_grid.regular import REGULAR_CHUNK_GRID, RegularChunkGridConfiguration
1923

2024
if TYPE_CHECKING:
2125
from collections.abc import Mapping
2226

23-
from zarr_metadata._common import JSONValue
27+
from zarr_metadata.testing._strategy import Strategies
2428
from zarr_metadata.v3._definition import ChunkGridDefinition
2529

2630
_MAX_LENGTH: Final = 16
27-
"""The longest chunk drawn along a dimension whose length is unknown."""
31+
"""The longest chunk drawn along a dimension whose length is unknown, before any factor its edges share."""
32+
33+
_MAX_CHUNK_LENGTH: Final = 2**63 - 1
34+
"""The longest chunk drawn at all: what a signed 64-bit size holds, as readers index with."""
2835

2936
_MAX_RUNS: Final = 5
3037
"""The most runs of equal lengths a rectilinear dimension is drawn with."""
3138

32-
_MAX_COUNT: Final = 4
33-
"""The most chunks a run is drawn with."""
39+
_FEW_CHUNKS: Final = 4
40+
"""The most chunks a short run is drawn with."""
41+
42+
_MAX_WRITTEN_OUT: Final = 64
43+
"""The most chunks a run is written out with, one length for each; a longer run is always a pair."""
44+
45+
_MAX_FACTOR: Final = 16
46+
"""The largest factor all of a dimension's edges are drawn to share."""
47+
48+
_MANY_CHUNKS: Final = 2**20
49+
"""The most chunks a run is drawn with along a dimension whose length is unknown or 0, into which it grows when the array is resized."""
3450

3551

3652
def _length(extent: int | None) -> st.SearchStrategy[int]:
37-
"""A chunk length along a dimension of `extent`: at least 1, and up to twice the extent when it is known and not 0."""
53+
"""A chunk length along a dimension of `extent`: at least 1, and up to twice the extent when it is known and not 0, within a signed 64-bit size."""
3854
if extent is None or extent == 0:
3955
return st.integers(1, _MAX_LENGTH)
40-
return st.integers(1, 2 * extent)
56+
return st.integers(1, min(2 * extent, _MAX_CHUNK_LENGTH))
4157

4258

43-
def _regular(shape: tuple[int, ...] | None) -> st.SearchStrategy[Mapping[str, JSONValue]]:
59+
def _regular(
60+
shape: tuple[int, ...] | None, _strategies: Strategies
61+
) -> st.SearchStrategy[RegularChunkGridConfiguration]:
4462
"""A chunk length for each dimension."""
4563
if shape is None:
4664
lengths = st.lists(_length(None), max_size=MAX_RANK).map(tuple)
4765
else:
4866
lengths = st.tuples(*(_length(extent) for extent in shape))
49-
return lengths.map(lambda chunk_shape: {"chunk_shape": chunk_shape})
67+
return lengths.map(lambda chunk_shape: RegularChunkGridConfiguration(chunk_shape=chunk_shape))
68+
5069

70+
def _count(extent: int | None, size: int) -> st.SearchStrategy[int]:
71+
"""How many chunks of `size` a run holds: a few, or as many as it takes to cover `extent`."""
72+
many = _MANY_CHUNKS if extent is None or extent == 0 else max(extent // size, _FEW_CHUNKS)
73+
return st.integers(1, _FEW_CHUNKS) | st.integers(1, many)
5174

52-
def _spelled_run(draw: st.DrawFn, size: int, count: int) -> list[JSONValue]:
53-
"""`count` chunks of `size`: one `[size, count]` pair, or the size written once for each."""
54-
if draw(st.booleans()):
75+
76+
def _spelled_run(draw: st.DrawFn, size: int, count: int) -> list[int | tuple[int, int]]:
77+
"""`count` chunks of `size`: one `[size, count]` pair, or, for a run short enough, the size written once for each."""
78+
if count > _MAX_WRITTEN_OUT or draw(st.booleans()):
5579
return [(size, count)]
5680
return [size] * count
5781

5882

5983
@st.composite
60-
def _edges(draw: st.DrawFn, extent: int | None) -> JSONValue:
84+
def _edges(draw: st.DrawFn, extent: int | None) -> tuple[int | tuple[int, int], ...]:
6185
"""Edge lengths along a dimension, covering `extent`, in runs spelled as pairs or written out.
6286
6387
Runs are drawn apart, so two of one size can sit side by side and a
64-
pair can count one chunk: spellings the canonical form merges. A
88+
pair can count one chunk: spellings the canonical form merges. A run
89+
can be long, since a pair costs the same however many chunks it
90+
counts, which is what the spelling is for. Its edges often share a
91+
factor, as they must for a shard to divide them into inner chunks
92+
longer than 1; edges drawn apart rarely do. A
6593
dimension of length zero, or of a length not known, may be covered by
6694
no edges at all.
6795
"""
6896
min_runs = 0 if extent is None or extent == 0 else 1
69-
runs = draw(
70-
st.lists(
71-
st.tuples(st.integers(1, _MAX_LENGTH), st.integers(1, _MAX_COUNT)),
72-
min_size=min_runs,
73-
max_size=_MAX_RUNS,
97+
factor = draw(st.just(1) | st.integers(2, _MAX_FACTOR))
98+
sizes = [
99+
factor * size
100+
for size in draw(
101+
st.lists(st.integers(1, _MAX_LENGTH), min_size=min_runs, max_size=_MAX_RUNS)
74102
)
75-
)
103+
]
104+
runs = [(size, draw(_count(extent, size))) for size in sizes]
76105
covered = sum(size * count for size, count in runs)
77106
if extent is not None and covered < extent:
78-
runs.append((extent - covered, 1))
79-
spelled: list[JSONValue] = []
107+
# Rounded up to the factor, so the last edge shares it, and past the dimension if need be.
108+
runs.append((-(-(extent - covered) // factor) * factor, 1))
109+
spelled: list[int | tuple[int, int]] = []
80110
for size, count in runs:
81111
spelled.extend(_spelled_run(draw, size, count))
82112
return tuple(spelled)
83113

84114

85-
def _rectilinear_dimension(extent: int | None) -> st.SearchStrategy[JSONValue]:
115+
def _rectilinear_dimension(extent: int | None) -> st.SearchStrategy[RectilinearDimSpec]:
86116
"""A bare length, which repeats until it covers the dimension, or edges that cover it."""
87117
return _length(extent) | _edges(extent)
88118

89119

90-
def _rectilinear(shape: tuple[int, ...] | None) -> st.SearchStrategy[Mapping[str, JSONValue]]:
120+
def _rectilinear(
121+
shape: tuple[int, ...] | None, _strategies: Strategies
122+
) -> st.SearchStrategy[RectilinearChunkGridConfiguration]:
91123
"""Inline chunk shapes, one entry for each dimension."""
92124
if shape is None:
93125
dimensions = st.lists(_rectilinear_dimension(None), max_size=MAX_RANK).map(tuple)
94126
else:
95127
dimensions = st.tuples(*(_rectilinear_dimension(extent) for extent in shape))
96-
return dimensions.map(lambda chunk_shapes: {"kind": "inline", "chunk_shapes": chunk_shapes})
128+
return dimensions.map(
129+
lambda chunk_shapes: RectilinearChunkGridConfiguration(
130+
kind="inline", chunk_shapes=chunk_shapes
131+
)
132+
)
97133

98134

99135
CHUNK_GRID_STRATEGIES: Final[Mapping[ChunkGridDefinition[Any], ChunkGridStrategy]] = {

‎packages/zarr-metadata/src/zarr_metadata/testing/_chunk_key_encoding.py‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,29 +10,35 @@
1010
from zarr_metadata.v3.chunk_key_encoding.default import (
1111
DEFAULT_CHUNK_KEY_ENCODING,
1212
DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR,
13+
DefaultChunkKeyEncodingConfiguration,
1314
)
1415
from zarr_metadata.v3.chunk_key_encoding.v2 import (
1516
V2_CHUNK_KEY_ENCODING,
1617
V2_CHUNK_KEY_ENCODING_SEPARATOR,
18+
V2ChunkKeyEncodingConfiguration,
1719
)
1820

1921
if TYPE_CHECKING:
2022
from collections.abc import Mapping
2123

2224
from zarr_metadata.v3._definition import ChunkKeyEncodingDefinition
2325

26+
_DEFAULT_SEPARATORS: Final = st.builds(DefaultChunkKeyEncodingConfiguration) | st.sampled_from(
27+
DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR
28+
).map(lambda separator: DefaultChunkKeyEncodingConfiguration(separator=separator))
29+
30+
_V2_SEPARATORS: Final = st.builds(V2ChunkKeyEncodingConfiguration) | st.sampled_from(
31+
V2_CHUNK_KEY_ENCODING_SEPARATOR
32+
).map(lambda separator: V2ChunkKeyEncodingConfiguration(separator=separator))
33+
2434
CHUNK_KEY_ENCODING_STRATEGIES: Final[
2535
Mapping[ChunkKeyEncodingDefinition[Any], ChunkKeyEncodingStrategy]
2636
] = {
2737
DEFAULT_CHUNK_KEY_ENCODING: ChunkKeyEncodingStrategy(
28-
configurations=st.fixed_dictionaries(
29-
{}, optional={"separator": st.sampled_from(DEFAULT_CHUNK_KEY_ENCODING_SEPARATOR)}
30-
)
38+
configurations=lambda _strategies: _DEFAULT_SEPARATORS
3139
),
3240
V2_CHUNK_KEY_ENCODING: ChunkKeyEncodingStrategy(
33-
configurations=st.fixed_dictionaries(
34-
{}, optional={"separator": st.sampled_from(V2_CHUNK_KEY_ENCODING_SEPARATOR)}
35-
)
41+
configurations=lambda _strategies: _V2_SEPARATORS
3642
),
3743
}
3844
"""A strategy for each chunk key encoding: a `separator`, or none, which means the encoding's default."""

0 commit comments

Comments
 (0)