Skip to content

fix(sharding): validate the inner codec chain against the array's fill value - #4633

Draft
d-v-b wants to merge 11 commits into
zarr-developers:mainfrom
d-v-b:fix/sharding-probe-threaded-fill-value
Draft

d-v-b wants to merge 11 commits into
zarr-developers:mainfrom
d-v-b:fix/sharding-probe-threaded-fill-value

Conversation

@d-v-b

@d-v-b d-v-b commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🤖 AI text below 🤖

Creating a sharded array no longer fails when the codecs inside the shard cannot encode the data type's default value, for example a scale_offset filter that maps only part of the data type's range. The inner codecs are now checked against the array's fill value, which must still be encodable.

Creating an array no longer rejects a codec placed after a data-type-changing codec such as cast_value because its configuration would be invalid for the array's original data type. Each codec is now checked against the data type it receives.

Fixes #4511. Supersedes #4526.

Related: d-v-b#449 fixes two data-loss bugs that predate this PR and are not fixed here: a sharding codec behind a transpose, and a 1-d array behind packbits. In both, the shard is checked against the array's chunk grid instead of the chunk it receives. d-v-b#449 builds on this PR, so this PR merges first.

Design notes

Sharding probe. ShardingCodec.validate probed the inner chain with dtype.default_scalar() as the fill value, because Codec.validate never receives the fill value. Value-transforming codecs (scale_offset, cast_value) encode the fill value in resolve_metadata, so a chain that encodes only a subrange of the data type was rejected for a value it never sees.

The inner-chain check now runs in ShardingCodec.evolve_from_array_spec, which already receives the threaded spec. It evolves, validates and resolves each inner codec against the spec the codecs before it leave, mirroring the loop in ArrayV3Metadata.__init__. ShardingCodec.validate keeps its structural checks (ndim, divisibility of the chunk grid).

The earlier approach in #4526 added a fill_value keyword to the public Codec.validate. That breaks third-party codecs that override validate with the old signature (TypeError). It also passed the array's own fill value through _validate_metadata's unthreaded loop, which rejected valid arrays with a filter before the sharding codec. Neither problem applies here, because Codec.validate is unchanged.

Unthreaded re-validation. ArrayV3Metadata._validate_metadata re-ran every codec's validate against the array's own data type, after __init__ had already validated each codec against the threaded spec. The second pass can only add wrong rejections, e.g. int16 → cast_value float32 → scale_offset(scale=0.5) (0.5 is not an int16). It is removed.

Behavior kept. An array whose fill value the inner chain cannot encode is still rejected, since an unwritten inner chunk holds the fill value. Nested sharding divisibility (#4480), inner structural errors, and outer indivisibility are rejected as before.

Rank check. The removed re-validation pass also refused a shard whose rank differs from the array's, for example a 2-d array whose packbits filter hands a 1-d chunk to a 1-d shard. Without that pass, such an array was accepted and lost data. ShardingCodec.validate now refuses a shard whose rank differs from the chunk grid's, so this PR refuses exactly the rank mismatches main refused. ArrayV3Metadata.__init__ checks the chunk grid's rank against the shape before validating codecs, so a mismatched grid still gets the grid error.

Not addressed (pre-existing). At the top level, ArrayV3Metadata.__init__ validates each codec against the array's chunk grid, not the chunk the codecs before it produce. A sharding codec behind a transpose, or behind a packbits filter on a 1-d array, is checked against the wrong shape, and writes lose data. The inner level handles this correctly. d-v-b#449 fixes this.

Tests
  • test_sharding_inner_chain_probed_with_array_fill_value: three layouts (filter inside the shard, filter before the sharding codec, nested sharding). Each is created, reads its fill value before any write, and round-trips a partial write through open_array. All three fail on main. The "behind-filter" fill value is chosen so that neither the default scalar nor the unthreaded fill value passes, so it also guards against probing with the wrong spec.
  • test_sharding_rejects_fill_value_inner_chain_cannot_encode: same layouts with an unencodable fill value. Pins the policy that these arrays are still rejected.
  • test_codec_validated_against_the_dtype_it_sees: int16 → cast_value float32 → scale_offset(scale=0.5), unsharded (fails on main) and sharded.
  • test_sharding_rejects_filter_that_changes_the_number_of_dimensions: a 2-d array whose packbits filter feeds a 1-d shard is refused, as on main.
  • test_refuses_exactly_the_fill_values_the_codecs_cannot_encode (new tests/test_zarr_metadata_conformance.py): draws array documents from zarr-metadata's hypothesis strategies. zarr-python must refuse a document if and only if encoding a chunk holding the fill value through the array→array codecs (the array's own, then each shard's) fails. Two slices run 2000 examples each: every definition zarr-metadata draws, and a slice limited to value-transforming codecs on numeric data types. Five known divergences are left out of the generated documents and pinned by strict xfail tests. Adds zarr-metadata[testing]==0.9.0 in a new conformance dependency group, which the min_deps env leaves out because zarr-metadata needs a newer typing-extensions; the module skips there. The nightly just hypothesis recipe also runs it, randomized.
  • How often the property catches each bug (20 random seeds per slice; "ci" is the derandomized profile): reverting both fixes, 20/20 in each slice; reverting only the re-validation removal, 16/20 and 19/20; reverting only the sharding probe, 17/20 and 18/20. Under the ci profile, each reverted fix fails at least one slice. The re-validation bug needs a data-type-changing codec, so it is caught only with cast-value-rs installed.
  • Tests for codecs, metadata, arrays and conformance: 3944 passed. mypy clean on the touched files.

🤖 Generated with Claude Code

…l value

Creating a sharded array failed when the inner codec chain could not
encode the data type's default scalar, e.g. a `scale_offset` filter that
maps only a subrange of the data type, even when the array's own fill
value encodes fine (zarr-developers#4511). `ShardingCodec.validate` probed the inner
chain with `dtype.default_scalar()`, since `validate` never receives the
fill value.

Run the inner-chain check from `ShardingCodec.evolve_from_array_spec`
instead, which receives the threaded spec: each inner codec is evolved,
validated and resolved against the spec the codecs before it leave,
including the fill value as those codecs encode it. An array whose fill
value the inner chain cannot encode is still rejected, because an
unwritten chunk holds the fill value.

Also drop the per-codec `validate` loop from
`ArrayV3Metadata._validate_metadata`. `__init__` has already validated
each codec against the threaded spec; the loop re-validated them against
the array's own data type, which rejected valid chains such as int16 ->
`cast_value` float32 -> `scale_offset` with a scale of 0.5.

Assisted-by: ClaudeCode:claude-opus-5-5
Assisted-by: ClaudeCode:claude-opus-5-5
Assisted-by: ClaudeCode:claude-opus-5-5
@codecov

codecov Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.30769% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 95.01%. Comparing base (13f4bf5) to head (0f260ad).

Files with missing lines Patch % Lines
src/zarr/core/metadata/v3.py 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4633      +/-   ##
==========================================
+ Coverage   95.00%   95.01%   +0.01%     
==========================================
  Files          96       96              
  Lines       14115    14114       -1     
==========================================
+ Hits        13410    13411       +1     
+ Misses        705      703       -2     
Files with missing lines Coverage Δ
src/zarr/codecs/sharding.py 95.79% <100.00%> (+<0.01%) ⬆️
src/zarr/core/metadata/v3.py 97.47% <50.00%> (+0.26%) ⬆️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Draw array documents from zarr-metadata's hypothesis strategies and hand
each to `ArrayV3Metadata.from_dict`. zarr-python may refuse a valid
document only for a fill value its codecs cannot encode, and must then
refuse it too with each shard's codecs moved out of the shard. Two slices
run: every definition, and the integer/float data types with the
value-transforming codecs, where fill value refusals are common.

Before this branch's fix the property fails for both bugs it fixes: the
unthreaded re-validation in `_validate_metadata`, and the sharding probe
with the data type's default scalar.

Known divergences are left out of the draw where possible and each is
pinned by a strict xfail test: object-spelled data types, `r*` raw bits,
integer-array `bytes` fill values, sharding behind `transpose`, hex
`cast_value` scalar map values, and zarr-metadata accepting empty
rectilinear edge lists (barred since zarr-extensions#78).

Adds `zarr-metadata[testing]==0.8.0` to the test dependency group.

Assisted-by: ClaudeCode:claude-opus-5-5
…deps

The conformance test exhausted memory on CI: zarr-python expands each
run-length pair of rectilinear edges into a list, and zarr-metadata draws
runs of up to millions of chunks. Draw no grid listing more than 10,000
chunks along an axis, and pin the divergence with a strict xfail test.

The min_deps env could not resolve: zarr-metadata 0.8.0 needs
typing-extensions>=4.16, and min_deps pins 4.14. Move zarr-metadata into
its own `conformance` dependency group, which the test envs include and
min_deps does not, and skip the module where it is not installed.

Assisted-by: ClaudeCode:claude-opus-5-5
d-v-b added 6 commits December 1, 2026 12:01
main now accepts a `bytes` fill value written as an array of integers
(zarr-developers#4493), so its strict xfail passed. Remove the test and the base64-only
fill value strategy, so the property draws both spellings again.

Assisted-by: ClaudeCode:claude-opus-5-5
zarr-metadata 0.9.0 refuses an empty list of rectilinear edge lengths
(zarr-developers#4636), so the strict xfail that pinned the difference passed. Remove it
and the exclusion.

Assisted-by: ClaudeCode:claude-opus-5-5
A filter that flattens each chunk (numcodecs.packbits) hands a 1-d shard
to the sharding codec, which checks its inner chunk shape against the
array's own N-d chunk grid. Dropping the second validation loop from
`_validate_metadata` let such an array through, and it lost the end of
each chunk. Refuse it, as main does.

Replace the conformance test's oracle. It accepted any ValueError raised
below `resolve_metadata`, so a codec that refused every fill value went
unseen. The test now encodes a chunk that holds the fill value and
requires zarr-python to refuse the document if and only if that fails.
Draw 2000 examples, because the profiles' 300 missed both bugs this
branch fixes under the derandomized ci profile. Draw every spelling, and
simplify only the data types. Run the test in the slow Hypothesis recipe.

Assisted-by: ClaudeCode:claude-opus-5-5
A chunk grid whose rank differs from the shape reached the sharding
codec's rank check first, which blamed the shard. Check the grid against
the shape before the codec loop, and name ranks in the shard message.

Assisted-by: ClaudeCode:claude-opus-5-5
@d-v-b

d-v-b commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

🤖 AI text below 🤖

The agent ran three rounds of adversarial review on this PR, each by a fresh reviewer agent. Round 1 found two serious problems, both fixed in 0a1bb3d. Rounds 2 and 3 found nothing serious that this PR introduces, so the review stopped there.

Findings and outcomes

Round 1 (whole PR)

  • Serious, fixed in 0a1bb3d: removing the re-validation pass also removed the only check that a shard's rank matches the array's. A 2-d bool array with a packbits filter in front of a 1-d shard was accepted, and writes lost data. ShardingCodec.validate now refuses that rank mismatch. A 40,000-document differential run in round 2 found no document this branch refuses that main accepts.
  • Serious, fixed in 0a1bb3d: the conformance property was too weak. Under the derandomized ci profile it passed with either fix reverted, so the description's claim that it "fails on main" was wrong. The oracle now encodes a chunk holding the fill value through the array→array codecs, and each slice runs 2000 examples. Catch rates are in the description's Tests section. The description is corrected.
  • Minor, fixed in 0a1bb3d: data types are rewritten to their simplest spelling instead of being filtered out; only transposes that move an axis are excluded; the hex scalar_map divergence text is corrected; the nightly just hypothesis recipe now runs the module.
  • Minor, kept: test_codec_validated_against_the_dtype_it_sees[sharded] passes on main. It stays as a regression guard for the sharded path.

Round 2 (fix commit and the code it touches): nothing serious.

  • Minor, kept: the module runs in the regular suite and in the nightly recipe. The nightly run is randomized, so it covers different documents.
  • Minor, noted: about 15% of "does not encode" draws are hidden by the hex scalar_map divergence, which a strict xfail pins.

Round 3 (0a1bb3d only): nothing serious that this PR introduces.

  • Serious, pre-existing on main, not fixed here: a sharding codec behind a transpose, and a 1-d array behind a packbits filter, are checked against the array's chunk grid instead of the chunk they receive, and writes lose data. The agent reproduced both on main and on this branch, and confirmed that fix(metadata): validate codecs after a transpose against the transposed chunk grid d-v-b/zarr-python#449 refuses both.
  • Minor, fixed in 0f260ad: a chunk grid whose rank differs from the shape got the shard's rank error instead of the grid error. The grid's rank is now checked before codecs are validated, and the shard message names ranks.

0f260ad was not reviewed by an agent. It moves one existing check earlier and rewords one message; the codec, metadata, array and conformance tests pass (3944 passed).

d-v-b added a commit to d-v-b/zarr-python that referenced this pull request Dec 3, 2026
…s#4633) into fix/transpose-chunk-grid-validation

Keep this branch's shard checks, which use the chunk grid the codecs before
the shard leave, in place of zarr-developers#4633's rank guard against the array's own grid:
a 2-d array whose packbits filter feeds a 1-d shard that divides the packed
chunk is valid. Drop zarr-developers#4633's rank test, which test_sharding_after_flattening_
filter_indivisible[2d] covers. Take zarr-developers#4633's fill-value oracle for the
conformance test, checking storage as well as reading, with the sharding
behind transpose divergence removed.

Assisted-by: ClaudeCode:claude-opus-5-5

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ShardingCodec.validate incorrectly assumes that Zdtype.default_scalar is always a valid value

1 participant