Skip to content

fix(array): broadcast written values to the selection before splitting them by chunk - #472

Draft
d-v-b wants to merge 4 commits into
mainfrom
fix/broadcast-write-across-chunks
Draft

d-v-b wants to merge 4 commits into
mainfrom
fix/broadcast-write-across-chunks

Conversation

@d-v-b

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

Copy link
Copy Markdown
Owner

🤖 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 raises ValueError before 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_fields asserting that broadcast whole-record writes raise IndexError, 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_like in _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_selection call after it, so the cast runs on the small value before it is broadcast.

What changed and why

_set_selection splits the value by each chunk's out_selection, and those selections index an array with the selection's shape. Values with any other shape were handed to the chunks unchanged:

  • A value that broadcasts ((1,), (1, n), (n,) into 2-D) was sliced past its end, so a region spanning more than one chunk along the broadcast axis raised could not broadcast input array from shape (0,) ....
  • A value that does not broadcast was sliced per chunk, and NumPy then broadcast each piece into its chunk. (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_selection helper in src/zarr/core/array.py runs once in _set_selection, after the dtype cast and the conversion to an NDBuffer. It applies NumPy assignment rules: drop leading length-1 axes beyond the selection's rank, then np.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 without reshape such as xarray.DataArray) go through np.asarray first. A value that does not broadcast raises ValueError before 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_selection keeps its existing exact-shape check, so it still rejects some values NumPy would broadcast.

Behavior changes that now match NumPy:

  • Writes with a wrong-rank or wrong-length value raise the broadcast ValueError up front, where they used to raise per chunk with different messages or write silently. Previously the chunked and sharded layouts disagreed on oindex[[3, 1], [0, 2]] = <(2, 2, 1) value>: chunked accepted it, sharded rejected it. Both reject it now.
  • An empty selection with a value that does not broadcast to it now raises instead of doing nothing.
Tests
  • test_set_selection_broadcasts_value: one test over 19 selection/value cases (basic, oindex including drop axes and ix_, mask, blocks), run under BatchedCodecPipeline and FusedCodecPipeline, v2, v3 and v3 sharded, write_empty_chunks on 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.matrix and a duck array without reshape.
  • 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[:] = v on 32e6 float32 elements, with a MemoryStore and no compressor. The stored data, 128 MB, is included in every number.

case Batched plain Batched sharded Fused plain Fused sharded
Python scalar, main → branch 160 → 160 256 → 256 156 → 152 264 → 264
0-d float64, main → branch 160 → 160 256 → 256 144 → 148 264 → 264
full-shape array, main → branch 128 → 128 160 → 160 128 → 128 256 → 256
(1, 4000) row into (8000, 4000) (branch only; failed on main) 160 256 156 384
full (8000, 4000) array, for comparison 160 256 144 384

Calls to merge_and_encode_chunk in 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, and np.broadcast_to dispatches to cupy.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

  • Pre-existing, out of scope: fields= writes on structured arrays overwrite every field (z["a"] = 7 stores (7, 7.0)). _set_selection never uses fields. 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.
  • Minor, fixed in 520299f: skipping 0-d selections left a silent-truncation path: z[2] = np.array([7, 8]) on shape (3,) with chunks (2,) was accepted. 0-d selections now go through the same check.
  • Minor, fixed in 520299f: xarray.DataArray / pandas.Series (no .reshape) and np.matrix values raised in the helper. Host values now go through np.asarray first.
  • Minor, kept: empty selections and wrong-rank values now raise, matching NumPy. Covered by tests and the changelog.
  • Nit, kept: mask writes accept extra leading length-1 axes, where NumPy's boolean assignment rejects values with more than one dimension. Harmless.
  • Fixed in 367521d: test_set_selection_rejects_value_with_wrong_rank matched 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 earlier astype(order=...) cast.

The loop stopped after two rounds in a row with no serious finding introduced by the change.

🤖 Generated with Claude Code

d-v-b and others added 4 commits November 29, 2026 21:29
…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 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.

1 participant