Repository navigation
Conversation
…g by chunk Writing an array that broadcasts to the selected region failed when the region spanned more than one chunk along a broadcast axis, and a value whose shape did not broadcast at all was silently truncated or repeated per chunk (e.g. `a[:] = np.arange(3)` on a shape-(4,) array with chunks (2,) stored [0, 1, 2, 2]). `_set_selection` now broadcasts the value to the selection shape as a read-only view after the dtype cast and buffer conversion, so memory stays per chunk and device arrays stay on device. One-element values become 0-d and take the scalar paths; 0-d values and 0-d selections are left untouched. A value that does not broadcast raises ValueError before any chunk is written. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…before writing The array-level broadcast check now rejects these values before any chunk is written, on chunked and sharded arrays alike, including the `(2, 2, 1)` oindex value the chunked path used to accept. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ost array-likes Review round 1 found that skipping 0-d selections left a silent-truncation path: `z[2] = np.array([7, 8])` on a shape-(3,) array with chunks (2,) stored the value as the size-1 edge chunk. 0-d selections now go through the same check: a one-element value is written as a scalar, anything else raises. It also found that values the helper could not reshape, `np.matrix` (always 2-D) and duck arrays without `reshape` such as `xarray.DataArray`, raised instead of broadcasting. Host values are converted with `np.asarray` first; device arrays are left as they are. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Nov 29, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
🤖 AI text below 🤖
Writing a value to an array selection now follows NumPy broadcasting however many chunks the selection spans. Values such as
np.array([7]), or one row written to a block of rows, no longer fail with a broadcast error. A value whose shape does not broadcast to the selection now raisesValueErrorbefore any chunk is written. Before, it could be silently truncated or repeated chunk by chunk:a[:] = np.arange(3)on a length-4 array with chunks of 2 stored[0, 1, 2, 2].Merge order with zarr-developers#4503 (single-field writes on structured arrays): the two merge without conflicts. zarr-developers#4503 has a strict xfail in
test_set_selection_with_fieldsasserting that broadcast whole-record writes raiseIndexError, which is the bug this PR fixes. Whichever PR merges second must remove that xfail.Merge order with #473 (same-itemsize structured writes): both edit the lines around
from_ndarray_likein_set_selection, so whichever merges second has a small textual conflict. Keep #473's dtype comparison before the conversion, and this PR's_broadcast_to_selectioncall after it, so the cast runs on the small value before it is broadcast.What changed and why
_set_selectionsplits the value by each chunk'sout_selection, and those selections index an array with the selection's shape. Values with any other shape were handed to the chunks unchanged:(1,),(1, n),(n,)into 2-D) was sliced past its end, so a region spanning more than one chunk along the broadcast axis raisedcould not broadcast input array from shape (0,) ....(3,)into a length-4 region with chunks of 2 stored[0, 1, 2, 2].(5,)dropped its last element. A chunk-shaped value written to one element in a size-1 edge chunk was stored as the whole chunk. None of these raised.The new
_broadcast_to_selectionhelper insrc/zarr/core/array.pyruns once in_set_selection, after the dtype cast and the conversion to anNDBuffer. It applies NumPy assignment rules: drop leading length-1 axes beyond the selection's rank, thennp.broadcast_to. The result is a read-only view, so no region-sized copy is made, and a device array stays on its device. A one-element value becomes 0-d, so it takes the existing scalar paths, including sharding's scalar fast path. Values that already match the selection, or are 0-d, are not touched. Host values that cannot change rank themselves (np.matrix, duck arrays withoutreshapesuch asxarray.DataArray) go throughnp.asarrayfirst. A value that does not broadcast raisesValueErrorbefore any chunk is written.The fix is in the shared write path, so it applies to
Array,AsyncArray, both codec pipelines, and v2/v3, sharded or not.Deliberate differences from NumPy: a one-element value written to a single element (
z[1, 2] = np.array([7])) is accepted for numeric dtypes too, where NumPy 2 raises.set_coordinate_selectionkeeps its existing exact-shape check, so it still rejects some values NumPy would broadcast.Behavior changes that now match NumPy:
ValueErrorup front, where they used to raise per chunk with different messages or write silently. Previously the chunked and sharded layouts disagreed onoindex[[3, 1], [0, 2]] = <(2, 2, 1) value>: chunked accepted it, sharded rejected it. Both reject it now.Tests
test_set_selection_broadcasts_value: one test over 19 selection/value cases (basic, oindex including drop axes andix_, mask, blocks), run under BatchedCodecPipeline and FusedCodecPipeline, v2, v3 and v3 sharded,write_empty_chunkson and off, and plain and structured dtypes. It checks results against NumPy assignment, starting from non-fill data so partial chunks merge with stored values. Against the base commit it fails 426 times.test_set_selection_rejects_value_that_does_not_broadcast: the error case. It covers the shapes that used to be truncated or repeated, the edge-chunk case, and an empty selection, and asserts the array is unchanged.test_set_selection_broadcasts_array_like:np.matrixand a duck array withoutreshape.test_set_selection_rejects_value_with_wrong_rank(existing): now matches the broadcast error, asserts nothing was written, and gains the(2, 2, 1)oindex case.uv run pytest tests -n 8: 14022 passed, 1318 skipped, 9 xfailed.Memory and the sharded scalar fast path
Peak tracemalloc for
a[:] = von 32e6 float32 elements, with a MemoryStore and no compressor. The stored data, 128 MB, is included in every number.(1, 4000)row into(8000, 4000)(branch only; failed on main)(8000, 4000)array, for comparisonCalls to
merge_and_encode_chunkin Fused sharded scalar writes are unchanged (2 on main and branch), so the scalar fast path still fires. A one-element value now also takes it (4 calls). A broadcast row costs the same as writing an already-allocated full array, so nothing region-sized is materialized. The GPU path was traced, not run, because no GPU was available. cupy values are converted to device arrays before the helper runs, andnp.broadcast_todispatches tocupy.broadcast_to.Adversarial review ledger
Round 1 had two fresh reviewers, one on correctness and one on compatibility/performance. Round 2 had one fresh reviewer.
Round 1
fields=writes on structured arrays overwrite every field (z["a"] = 7stores(7, 7.0))._set_selectionnever usesfields. This happens on main for scalar and full-shape values. With this change, broadcast field values on multi-chunk regions now reach the same path instead of raising. The agent proposed a separate fix.z[2] = np.array([7, 8])on shape(3,)with chunks(2,)was accepted. 0-d selections now go through the same check.xarray.DataArray/pandas.Series(no.reshape) andnp.matrixvalues raised in the helper. Host values now go throughnp.asarrayfirst.test_set_selection_rejects_value_with_wrong_rankmatched the old error text.Round 2: nothing serious. Around 830 differential cases against NumPy across pipelines, formats, sharding,
write_empty_chunks, F-ordered, strided and big-endian values, masked arrays, dask, xarray, pandas, array_api_strict, memoryview, vlen bytes, and rectilinear grids. Read-only zero-stride views went through transpose, crc32c, F order, Delta and Blosc on both pipelines. Nit, pre-existing: a pandas Series whose dtype differs from the array's fails at the earlierastype(order=...)cast.The loop stopped after two rounds in a row with no serious finding introduced by the change.
🤖 Generated with Claude Code