Skip to content

fix(experimental): keep CacheStore entries consistent under concurrent reads and writes - #495

Draft
d-v-b wants to merge 13 commits into
fix/cachestore-passthrough-mutatorsfrom
fix/cachestore-atomic-tracking
Draft

d-v-b wants to merge 13 commits into
fix/cachestore-passthrough-mutatorsfrom
fix/cachestore-atomic-tracking

Conversation

@d-v-b

@d-v-b d-v-b commented Dec 4, 2026 •

Copy link
Copy Markdown
Owner

🤖 AI text below 🤖

CacheStore keeps its cache consistent with the source store when reads and writes run concurrently. A read that races a write no longer caches the value the write replaced, values larger than max_size are no longer written to the cache store, and failed, canceled or partly failed writes and deletions no longer leave stale entries. Canceling a write no longer stops it from reaching the source store.

Stack: this PR is stacked on #494 (fix/cachestore-passthrough-mutators), which is stacked on upstream zarr-developers#4696 (now merged). Merge #494 first. This branch has upstream main merged in (for zarr-developers#4696); #494 has not, so until it does, this PR's diff also shows those upstream commits. The commits to review are the ones after 2f24bc9d6.

Design

All cache changes now go through two locked primitives:

  • _install_entry writes the cache store and tracks the entry in one step under the lock.
  • _drop_entry releases tracking and then deletes from the cache store, also under the lock.

Tracking is the one source of truth for full-key hits: only tracked keys are served. A failed cache-store delete, or data a persistent cache held from an earlier session, can cost a hit but cannot serve a stale value.

Races between reads and writes. Every source read and write registers a _PendingOp before it starts. When a write completes, it marks the other in-flight ops on its key as no longer current. An overlapped read does not cache what it fetched. An overlapped write drops the entry rather than guess which value the source kept. delete_dir and clear mark every op under their prefix. Ops are forgotten when they settle, so pending holds only in-flight work.

Cancellation. Each source mutation runs as one task together with its cache update (_run_to_completion). Canceling the caller does not stop the cache from following the source, including for LocalStore, which writes in a thread that keeps running after a cancel. An error raised after the caller left is logged.

Failures.

Decisions worth a maintainer look:

  1. Canceling a write does not stop it (set, delete, set_if_not_exists, delete_dir, clear). This keeps the cache exact for thread-backed stores. The cost is that, on natively async stores, a canceled write can still land after a later write to the same key. The alternatives that keep writes cancelable either leave the cache stale after a cancel or never cache that key again.
  2. Failed bulk deletions check exists rather than dropping everything under the prefix. Both reviewers in round 1 preferred dropping everything, which is simpler and always safe, but it would reverse fix: invalidate CacheStore entries after bulk deletion zarr-developers/zarr-python#4696's pinned "source error preserves cache" behavior. Switching is a small change if preferred.
  3. Cache-store writes and evictions are serialized under the global lock. Hits are lock-free. A slow cache store makes concurrent misses take turns (reviewers measured 50 × 10 ms misses going from 0.01 s to 0.59 s). Per-key cache I/O would remove this, at the cost of more code.
Tests
  • CacheStoreMachine, a Hypothesis state machine, drives random sequences of set, get (full and byte-range), delete, set_if_not_exists, _set_many, delete_dir, clear and clear_cache. Some steps run concurrently, some go through a with_read_only view.

    • It uses small max_size values and both cache_set_data settings.
    • The stores yield a drawn number of times on every call.
    • The source fails deletes at random, so delete_dir and clear fail partway.
    • After every step, _assert_cache_coherent checks:
      • current_size == sum(key_sizes);
      • tracking structures agree;
      • the cache store holds exactly the tracked keys;
      • no op stays registered;
      • every cached value equals the source's current value.
    • Each solo get must return the source's value, and no step may leave a task running.
    • The machine fails on fix(experimental): keep CacheStore coherent for every inherited write #494's head (2f24bc9) and passes here under the default, ci and nightly profiles (about 6 s, 6 s and 18 s).
  • Deterministic tests cover each race and failure path the reviews found:

    • read miss vs write;
    • a read's settle queued ahead of a write's;
    • overlapping writes;
    • canceled writes, both mid-source-call and while waiting for the lock;
    • canceled reads;
    • oversized values;
    • cache-store failures;
    • partly failed delete_dir/clear (with and without exists failing, range-only keys, reads in flight);
    • clear_cache with reads in flight;
    • failing source reads;
    • exact max_size;
    • untracked cache data;
    • errors logged after cancel.

    Each fails on the code before its fix.

  • Mutation testing: 39 mutants of cache_store.py were written by a reviewer, run under the ci profile. All non-equivalent mutants are killed. The four survivors are equivalent or only drop more entries.

Adversarial review record

Fresh reviewer agents got the diff and files each round. Every finding was reproduced with a probe before it was fixed.

Round 1 (296f991), serious findings in both the code and the tests:

  • Fixed in 2d08a7e:
    • a write canceled during the source call left the old value cached (reworked in 8a49c61);
    • a failed eviction served the replaced value;
    • delete_dir dropped byte ranges only after cache-store I/O.
  • Fixed in c321e9e:
    • a partly failed delete_dir left deleted keys cached;
    • test gaps: a race CI would miss, a machine that rarely evicted, pending leaks unchecked, no coherence check in the targeted tests.
  • Not fixed:
    • the global lock serializing cache I/O is kept and documented (decision 3);
    • LocalStore.delete on a directory and MemoryStore.clear ignoring read_only are store bugs, left as follow-ups.

Round 2 (c321e9e), serious findings:

  • Fixed in 8a49c61:
    • exists failing during a failed deletion dropped nothing;
    • canceling a thread-backed write let a read re-cache the old value before the thread landed (now one task per mutation);
    • hits served untracked data;
    • _set_many returned while sibling writes still ran, which made the machine flaky (plus a leftover-task assertion in 52e5897);
    • clear_cache was unshielded.
  • Fixed in 52e5897: test gaps (failed deletions racing reads, range-only keys, clear_cache supersession, boundary sizes, failing reads), plus American spelling.
  • Not fixed: ObjectStore.delete_dir keeps deleting after gather raises. That is an ObjectStore bug, left as a follow-up.

Round 3 (52e5897), only the fix diff:

  • Fixed in 6d624cf:
    • a cache-store failure during a failed bulk delete left later keys tracked and stale;
    • an error after a cancel was reported as "never retrieved".
  • Kept and documented: canceling no longer stops writes (decision 1).
  • Accepted and documented: the budget can be exceeded after a failed cache-store delete. That data is never served.

Round 4 (6d624cf): no serious findings.

  • Applied in 6558a90: two nits.
  • Accepted:
    • a CancelledError from a cache-store delete replaces the source error (pre-existing behavior);
    • deletes after a failed bulk delete run with no concurrency limit.

Round 5 (6558a90, upstream merge, fragment): no serious or minor findings; two nits not acted on (fork PR numbers in fragment names; cache-store error masks source error on a doubly failed bulk delete, pre-existing). Review stopped after rounds 4 and 5 came back clean.

🤖 Generated with Claude Code

d-v-b and others added 13 commits December 4, 2026 13:55
…s#4697)

* chore(mypy): remove the no-op strict = false override

mypy applies `strict` only when it is true, so `strict = false` in a
per-module override is ignored. The 14 entries listed there (modules and
globs) were already checked strictly. Remove the block, and reword the
TODO on the `ignore_errors` list that pointed at it.

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

* test(fsspec): take test_fsspec off the mypy ignore list

Narrow the subgroup returned by `AsyncGroup.getitem` to `AsyncGroup`
before calling `group_keys`, which was the module's only mypy error, and
remove `tests.test_store.test_fsspec` from the `ignore_errors` list so the
module's own code is type-checked like the rest of the tests.

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

* test(v2): ignore numcodecs' Pickle deprecation warning in pickle tests

numcodecs main now warns that its Pickle codec is deprecated whenever one
is created, and the suite turns warnings into errors, so the pickle
decode-gate tests in test_v2.py fail in the upstream-dependencies job.
Those tests create Pickle codecs on purpose, so ignore that warning for
them. Released numcodecs doesn't warn, so the filter ignores the warning
rather than requiring it.

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

* test(fsspec): use get_group instead of narrowing getitem's result

`AsyncGroup.get_group` returns an `AsyncGroup` and raises if the member is
an array, so the test needs no isinstance assert to type-check.

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

* test(v2): match the Pickle deprecation comment to upstream zarr-developers#4680

Assisted-by: ClaudeCode:claude-opus-5-5
Writing a cache entry (cache-store write plus size/LRU tracking) and
dropping one (cache-store delete plus tracking release) were separate,
unlocked steps spread over many call sites. Concurrent reads and writes
could leave untracked data in the cache store, tracking with nothing
behind it, or a stale value cached forever:

- a read miss fetched the source outside the lock and then cached the
  result, even if a `set` or `delete` of the same key completed in
  between;
- values larger than `max_size` were written to the cache store before
  the size check rejected them, and stayed there untracked;
- overlapping `set` calls on one key installed their values in lock
  order, which need not match the order the source applied them.

`_install_entry` and `_drop_entry` now do the whole change under the
lock. Every source read and write registers a `_PendingOp` before it
starts; a write that completes marks the other operations on its key as
overlapped. An overlapped read does not cache what it fetched, and an
overlapped write drops the entry instead of caching its value.
`delete_dir` and `clear` mark every operation under their prefix.
Settling the cache after a source operation is shielded from
cancellation. A source operation that raises still leaves the cache as
it was.

A Hypothesis state machine drives random, partly concurrent sequences of
every operation through yielding stores and checks after each step that
tracking matches the cache store exactly and that everything cached
equals the source.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…r-developers#4669)

* fix(sharding): keep whole-shard reads in the buffer's own memory

The fused pipeline's fast path for reading a whole uncompressed shard
copied the shard to host memory with `as_numpy_array()`, then assigned
each chunk into the output buffer. Under `zarr.config.enable_gpu()` the
output is a CuPy array, which refuses host arrays, so the read failed.
The fast path now uses `as_array_like()`, as `BytesCodec` does.

The stored-byte-order view dtype is now computed by one helper,
`BytesCodec._stored_dtype`, shared by the per-chunk and fast paths.
It handles structured data types, so the fast path no longer has to
decline them.

Closes zarr-developers#4654

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

* docs(changes): add fragment for the whole-shard device read fix

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

* test(sharding): draw structured data types in the bulk-decode property test

The whole-shard fast path now takes structured data types, so its
equivalence test with the per-chunk path draws a mixed-endian struct.
The changelog fragment now says the structured fast path applies to
FusedCodecPipeline only.

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

* docs(changes): number the fragment for the upstream PR

Assisted-by: ClaudeCode:claude-opus-5-5
A caller cancelled while the source write was in flight skipped the
cache update, but the write may still have landed (LocalStore writes in
a thread; remote stores may commit before responding). The old value
then stayed cached. `set`, `delete`, `set_if_not_exists`, `delete_dir`
and `clear` now drop the affected entries when cancelled; a store
exception still leaves the cache as it was.

A failed eviction while installing an entry also left the replaced
value in the cache store untracked, where reads would serve it; the
entry is now dropped on any failure there. `delete_dir` and `clear`
release tracking and byte-range entries before the cache-store I/O, so
a cache-store failure cannot leave in-memory ranges of deleted keys.

Found in adversarial review of the previous commit.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`Store.delete_dir` and `clear` delete key by key, so one that raises may
have deleted some keys; those stayed cached and were served afterwards.
A failed `delete_dir` or `clear` now checks which tracked, range-cached
or in-flight keys under its prefix the source no longer has and drops
those entries, keeping the rest (so a deletion that fails before
touching the source still leaves the cache as it was). A failed
single-key write may also have reached the source, so it drops the
key's entry, as a cancelled one already did.

Tests:
- one coherence helper, used by the state machine and the targeted
  tests, also checks that the cache store holds exactly the tracked
  keys, that no operation stays registered, and that no empty per-key
  range dict is left;
- the state machine draws reads and writes more often and small
  `max_size` values, so it fills and evicts; it no longer overrides the
  Hypothesis profile's example and step counts; it checks `_set_many`
  leaves the last value for each key in the source;
- new deterministic tests: a read's cache update queued ahead of a
  write's, a cancelled read, cache-store failures while installing, and
  a partly failed `delete_dir`/`clear`.

Every mutant from the adversarial review is now killed under the CI
Hypothesis profile.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cancelling a write's caller does not stop a thread-backed source call
(LocalStore writes in `asyncio.to_thread`), so dropping the entry at
cancellation let a read in the window re-cache the old value before the
thread landed. Each source mutation and its cache update now run as one
task that cancelling the caller does not stop, so the cache settles
when the source call has really ended, and the special cancellation
branches go away.

Tracking is now the one source of truth for full-key hits: only tracked
keys are served, and `_drop_entry` releases tracking before deleting
from the cache store. A failed cache-store delete, or data a persistent
cache store held from an earlier session, can then cost a hit but never
serve a stale value.

A failed `delete_dir`/`clear` now also drops entries when asking the
source whether a key still exists fails. `_set_many` waits for every
write before raising the first error, instead of returning while the
others still run. Hits no longer take the lock to update the LRU order.
`clear_cache` is shielded.

Found in the second adversarial review round.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The state machine's source now fails deletes at random, so `delete_dir`
and `clear` fail partway while reads and writes are in flight; its
`clear` deletes key by key and checks read-only, like a real store. Its
`exists` yields, operations are reweighted so the cache fills, errors
are matched by message, and a step that leaves a task running fails by
name instead of leaking into the next example.

New targeted tests: a failed deletion of keys cached only as byte
ranges, and of keys with a read in flight; `clear_cache` keeping reads
in flight supersedable; a failing source read; filling `max_size`
exactly. Coherence is checked before the reads that could repair it.
Prose uses American spelling.

Found in the second adversarial review round.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tion guide (zarr-developers#4694)

Scalar indexing returned a NumPy scalar in Zarr-Python 2 and returns a
0-dimensional numpy.ndarray in Zarr-Python 3, following the Python array
API standard. Arrays whose shape is () changed in the other direction.
The migration guide covered neither, so the change was only visible from
the Array.__getitem__ doctest.
…rs#4696)

* fix: invalidate CacheStore entries after bulk deletion

* chore: use the pull request number for the changelog
… I/O

When a source `delete_dir`/`clear` failed and the cache store then
failed to delete the first absent key, settling stopped there and the
later absent keys stayed tracked, so reads served values the source no
longer had. All absent keys are now released before any cache-store
delete, the deletes run together, and the first failure is raised.

Canceling a write's caller already did not stop the write; this is now
documented on the class. An error the write raises after its caller was
canceled is logged instead of being reported by asyncio as never
retrieved, and the task is kept referenced until it finishes.

Found in the third adversarial review round.

Assisted-by: ClaudeCode:claude-opus-5-5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ic-tracking

# Conflicts:
#	tests/test_experimental/test_cache_store.py
Match how `_set_many` picks errors out of `gather` results, and wait in
the orphan-logging test until the operation has finished rather than a
fixed number of loop turns.

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>
@d-v-b

d-v-b commented Dec 4, 2026

Copy link
Copy Markdown
Owner Author

🤖 AI text below 🤖

Round 5 of the adversarial review (6558a90, the upstream merge 6b5ddd1, and the fragment 4c572bb) found nothing serious or minor. Rounds 4 and 5 both came back without serious findings, so the review loop is finished.

Round 5 details

Upstream merge

Code and test changes

  • The isinstance(result, BaseException) filter is correct.
  • The orphan-wait loop cannot race the log assertion: the done callback removes the task from orphans and logs in the same synchronous step.
  • 136 tests pass under the default and ci Hypothesis profiles with -W error.

Nits, not acted on

  • The fragments 494/495 carry fork PR numbers. They need renaming to the upstream PR number when this goes upstream.
  • When a failed bulk delete is followed by a failed cache-store delete, the caller sees the cache-store error, with the source error kept as __context__. That behavior was already there before this PR.

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.

3 participants