From 5d8689ba93a88bdb49226ad1d0c8ac4fec5fa236 Mon Sep 17 00:00:00 2001 From: Davis Bennett Date: Fri, 4 Dec 2026 13:55:17 +0100 Subject: [PATCH 01/12] chore(mypy): remove the no-op strict = false override (#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 #4680 Assisted-by: ClaudeCode:claude-opus-5-5 --- pyproject.toml | 23 +---------------------- tests/test_store/test_fsspec.py | 2 +- 2 files changed, 2 insertions(+), 23 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 97901a73df..36ca94ab62 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -373,30 +373,9 @@ strict = true warn_unreachable = true enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool", "truthy-iterable"] +# TODO: fix the type errors in these modules and remove them from this list [[tool.mypy.overrides]] module = [ - "tests.package_with_entrypoint.*", - "zarr.testing.stateful", - "tests.test_codecs.test_transpose", - "tests.test_config", - "tests.test_store.test_zip", - "tests.test_store.test_local", - "tests.test_store.test_memory", - "tests.test_codecs.test_codecs", - "tests.test_metadata.*", - "tests.test_store.test_core", - "tests.test_store.test_logging", - "tests.test_store.test_object", - "tests.test_store.test_stateful", - "tests.test_store.test_wrapper", -] -strict = false - -# TODO: Move the next modules up to the strict = false section -# and fix the errors -[[tool.mypy.overrides]] -module = [ - "tests.test_store.test_fsspec", "tests.test_group", "tests.test_indexing", "tests.test_properties", diff --git a/tests/test_store/test_fsspec.py b/tests/test_store/test_fsspec.py index f26a6f316a..faea1caf0f 100644 --- a/tests/test_store/test_fsspec.py +++ b/tests/test_store/test_fsspec.py @@ -488,7 +488,7 @@ async def test_fsspec_store_list_nested_via_reference_filesystem(path: str) -> N ] group = await zarr.api.asynchronous.open_group(store, mode="r") - subgroup = await group.getitem("a") + subgroup = await group.get_group("a") assert [name async for name in subgroup.group_keys()] == ["b"] From 296f991127b6990e705c702ebe0b1319e3693236 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 14:10:33 +0100 Subject: [PATCH 02/12] fix(experimental): update CacheStore entries in one locked step 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 --- src/zarr/experimental/cache_store.py | 342 ++++++++++------- tests/test_experimental/test_cache_store.py | 389 +++++++++++++++++++- 2 files changed, 593 insertions(+), 138 deletions(-) diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index 866b89834f..38d3ab2bf6 100644 --- a/src/zarr/experimental/cache_store.py +++ b/src/zarr/experimental/cache_store.py @@ -14,7 +14,7 @@ logger = logging.getLogger(__name__) if TYPE_CHECKING: - from collections.abc import Iterable + from collections.abc import Coroutine, Iterable from zarr.core.buffer.core import Buffer, BufferPrototype @@ -35,6 +35,23 @@ class _CacheState: evictions: int = 0 key_insert_times: dict[_CacheEntryKey, float] = field(default_factory=dict) range_cache: dict[str, dict[ByteRequest, Buffer]] = field(default_factory=dict) + pending: dict[str, set[_PendingOp]] = field(default_factory=dict) + + +@dataclass(slots=True, eq=False) +class _PendingOp: + """ + A source read or write of `key` that is in flight. + + `current` turns false when a write to `key` reaches the source and settles while this + operation is in flight. A read that is no longer current may have fetched the value that + write replaced, so it does not cache it. A write that is no longer current cannot tell + whether its value or the other write's value ended up in the source, so it drops the + cache entry instead of caching its value. + """ + + key: str + current: bool = True class CacheStore(WrapperStore[Store]): @@ -50,6 +67,11 @@ class CacheStore(WrapperStore[Store]): pollute the filesystem (or other persistent backend). Both caches share the same ``max_size`` budget and LRU eviction policy. + Concurrent reads and writes keep the cache consistent with the source store. A read that + misses while a write to the same key is in flight does not cache the value that write + replaces, and when two writes to one key overlap, the key's entry is dropped rather than + guessing which value the source kept. + Parameters ---------- store : Store @@ -156,27 +178,61 @@ def _is_key_fresh(self, entry_key: _CacheEntryKey) -> bool: return elapsed < self.max_age_seconds async def _accommodate_value(self, value_size: int) -> None: - """Ensure there is enough space in the cache for a new value. + """Evict least recently used entries until a value of `value_size` bytes fits. Must be called while holding self._state.lock. """ if self.max_size is None: return - - # Remove least recently used items until we have enough space while self._state.current_size + value_size > self.max_size and self._state.cache_order: - # Get the least recently used key (first in OrderedDict) - lru_key = next(iter(self._state.cache_order)) - await self._evict_key(lru_key) + await self._evict_key(next(iter(self._state.cache_order))) async def _evict_key(self, entry_key: _CacheEntryKey) -> None: - """Evict a cache entry. + """Drop a cache entry to make room, counting it as an eviction. Must be called while holding self._state.lock. + """ + await self._drop_entry(entry_key) + self._state.evictions += 1 - For ``str`` keys the entry is deleted from the Store-backed cache. - For ``(str, ByteRequest)`` keys the entry is removed from the - in-memory range cache. + async def _install_entry(self, entry_key: _CacheEntryKey, value: Buffer) -> None: + """Make `value` the cache entry for `entry_key`: write it and track its size and recency. + + A value larger than `max_size` is not cached, and any entry it replaces is dropped. + Writing and tracking happen in this one locked step, so the cache never holds data + that the size budget does not count. + + Must be called while holding self._state.lock. + """ + value_size = len(value) + if self.max_size is not None and value_size > self.max_size: + await self._drop_entry(entry_key) + return + # Release the old entry first, so making room counts only the other entries. + self._remove_from_tracking(entry_key) + await self._accommodate_value(value_size) + if isinstance(entry_key, str): + try: + await self._cache.set(entry_key, value) + except BaseException: + # The write may have left the old value behind, untracked. + await self._cache.delete(entry_key) + raise + else: + base_key, byte_range = entry_key + self._state.range_cache.setdefault(base_key, {})[byte_range] = value + self._state.cache_order[entry_key] = None + self._state.current_size += value_size + self._state.key_sizes[entry_key] = value_size + self._state.key_insert_times[entry_key] = time.monotonic() + + async def _drop_entry(self, entry_key: _CacheEntryKey) -> None: + """Delete a cache entry's data and release its tracking. + + For `str` keys the entry is deleted from the Store-backed cache, whether or not it is + tracked. For `(str, ByteRequest)` keys it is removed from the in-memory range cache. + + Must be called while holding self._state.lock. """ if isinstance(entry_key, str): await self._cache.delete(entry_key) @@ -187,40 +243,7 @@ async def _evict_key(self, entry_key: _CacheEntryKey) -> None: per_key.pop(byte_range, None) if not per_key: del self._state.range_cache[base_key] - self._remove_from_tracking(entry_key) - self._state.evictions += 1 - - async def _track_entry(self, entry_key: _CacheEntryKey, value: Buffer) -> bool: - """Register *entry_key* in the shared size / LRU tracking. - - Returns ``True`` if the entry was tracked, ``False`` if the value - exceeds ``max_size`` and was skipped. Callers should roll back any - data they already stored when this returns ``False``. - - This method holds the lock for the entire operation to ensure atomicity. - """ - value_size = len(value) - - # Check if value exceeds max size - if self.max_size is not None and value_size > self.max_size: - return False - - async with self._state.lock: - # Release the old entry first, so making room cannot evict the entry being replaced - # and release its size a second time. - self._remove_from_tracking(entry_key) - - # Make room for the new value - await self._accommodate_value(value_size) - - # Update tracking atomically - self._state.cache_order[entry_key] = None - self._state.current_size += value_size - self._state.key_sizes[entry_key] = value_size - self._state.key_insert_times[entry_key] = time.monotonic() - - return True async def _update_access_order(self, entry_key: _CacheEntryKey) -> None: """Update the access order for LRU tracking. @@ -254,43 +277,136 @@ def _invalidate_range_entries(self, key: str) -> None: for byte_range in per_key: self._remove_from_tracking((key, byte_range)) + async def _reset_cache(self) -> None: + """Empty the Store-backed cache, the range cache, and all tracking. + + Must be called while holding self._state.lock. + """ + await self._cache.clear() + self._state.key_insert_times.clear() + self._state.cache_order.clear() + self._state.key_sizes.clear() + self._state.range_cache.clear() + self._state.current_size = 0 + # ------------------------------------------------------------------ - # get helpers + # source operations in flight # ------------------------------------------------------------------ - async def _cache_miss( - self, key: str, byte_range: ByteRequest | None, result: Buffer | None + def _begin(self, key: str) -> _PendingOp: + """Register a source read or write of `key`, before it starts.""" + op = _PendingOp(key) + self._state.pending.setdefault(key, set()).add(op) + return op + + def _end(self, op: _PendingOp) -> None: + """Forget a source operation registered by `_begin`, so no later write marks it.""" + ops = self._state.pending.get(op.key) + if ops is not None: + ops.discard(op) + if not ops: + del self._state.pending[op.key] + + def _supersede(self, key: str) -> None: + """Mark every source operation on `key` still in flight as overlapped by a write. + + Must be called while holding self._state.lock, after the write reached the source. + """ + for op in self._state.pending.pop(key, ()): + op.current = False + + async def _settle_read( + self, op: _PendingOp, byte_range: ByteRequest | None, result: Buffer | None ) -> None: - """Handle a cache miss by storing or cleaning up after a source-store fetch.""" - if result is None: - if byte_range is None: - await self._cache.delete(key) - async with self._state.lock: - self._remove_from_tracking(key) + """Cache what a source read returned, unless a write to its key completed meanwhile.""" + entry_key: _CacheEntryKey = op.key if byte_range is None else (op.key, byte_range) + async with self._state.lock: + self._end(op) + if not op.current: + return + if result is None: + await self._drop_entry(entry_key) else: - entry_key: _CacheEntryKey = (key, byte_range) - async with self._state.lock: - per_key = self._state.range_cache.get(key) - if per_key is not None: - per_key.pop(byte_range, None) - if not per_key: - del self._state.range_cache[key] - self._remove_from_tracking(entry_key) - else: - if byte_range is None: - await self._cache.set(key, result) - await self._track_entry(key, result) + await self._install_entry(entry_key, result) + + async def _write( + self, key: str, write: Coroutine[Any, Any, None], value: Buffer | None + ) -> None: + """Run `write`, a write of `key` to the source store, then settle the cache for it. + + A write that raises is taken to have left the source unchanged, so the cache is left + as it was. Once the write succeeded, settling is shielded from cancellation: the + cache must follow the source even if the caller is cancelled while waiting for the + lock. + """ + op = self._begin(key) + try: + await write + except BaseException: + self._end(op) + raise + await asyncio.shield(self._settle_write(op, value)) + + async def _settle_write(self, op: _PendingOp, value: Buffer | None) -> None: + """Bring the cache in line with a completed source write of `op.key`. + + `value` is cached when it is given and no other write to the key overlapped this one. + Otherwise the source's value is unknown here, and the key's entry is dropped. Either + way, its byte-range entries are dropped and the reads in flight for it will not cache + what they fetched. + """ + async with self._state.lock: + self._end(op) + overlapped = not op.current + self._supersede(op.key) + self._invalidate_range_entries(op.key) + if value is None or overlapped: + await self._drop_entry(op.key) else: - entry_key = (key, byte_range) - self._state.range_cache.setdefault(key, {})[byte_range] = result - tracked = await self._track_entry(entry_key, result) - if not tracked: - # Value too large for the cache — roll back the insertion - per_key = self._state.range_cache.get(key) - if per_key is not None: - per_key.pop(byte_range, None) - if not per_key: - del self._state.range_cache[key] + await self._install_entry(op.key, value) + + async def _settle_delete_dir(self, prefix: str) -> None: + """Drop every cache entry under `prefix` after a source `delete_dir`.""" + if prefix != "" and not prefix.endswith("/"): + prefix += "/" + async with self._state.lock: + for key in [key for key in self._state.pending if key.startswith(prefix)]: + self._supersede(key) + await self._cache.delete_dir(prefix) + for key in [key for key in self._state.range_cache if key.startswith(prefix)]: + self._invalidate_range_entries(key) + for entry_key in list(self._state.key_sizes): + if isinstance(entry_key, str) and entry_key.startswith(prefix): + self._remove_from_tracking(entry_key) + + async def _settle_clear(self) -> None: + """Drop every cache entry after a source `clear`.""" + async with self._state.lock: + for key in list(self._state.pending): + self._supersede(key) + await self._reset_cache() + + # ------------------------------------------------------------------ + # get helpers + # ------------------------------------------------------------------ + + async def _fetch( + self, key: str, prototype: BufferPrototype, byte_range: ByteRequest | None + ) -> Buffer | None: + """Read from the source store and cache the result. + + Like a write, settling is shielded from cancellation, so a cancelled read cannot leave + the cache half updated. + """ + self._state.misses += 1 + op = self._begin(key) + try: + result = await super().get(key, prototype, byte_range) + except BaseException: + self._end(op) + raise + await asyncio.shield(self._settle_read(op, byte_range, result)) + return result async def _get_try_cache( self, key: str, prototype: BufferPrototype, byte_range: ByteRequest | None = None @@ -313,21 +429,13 @@ async def _get_try_cache( self._state.hits += 1 await self._update_access_order(entry_key) return cached_buf - - # Cache miss — fetch from source store - self._state.misses += 1 - result = await super().get(key, prototype, byte_range) - await self._cache_miss(key, byte_range, result) - return result + return await self._fetch(key, prototype, byte_range) async def _get_no_cache( self, key: str, prototype: BufferPrototype, byte_range: ByteRequest | None = None ) -> Buffer | None: """Get data directly from source store and update cache.""" - self._state.misses += 1 - result = await super().get(key, prototype, byte_range) - await self._cache_miss(key, byte_range, result) - return result + return await self._fetch(key, prototype, byte_range) @property def _supports_sync_io(self) -> bool: @@ -377,17 +485,7 @@ async def set(self, key: str, value: Buffer) -> None: value : Buffer The data to store """ - await super().set(key, value) - # Invalidate all cached byte-range entries (source data changed) - async with self._state.lock: - self._invalidate_range_entries(key) - if self.cache_set_data: - await self._cache.set(key, value) - await self._track_entry(key, value) - else: - await self._cache.delete(key) - async with self._state.lock: - self._remove_from_tracking(key) + await self._write(key, super().set(key, value), value if self.cache_set_data else None) async def delete(self, key: str) -> None: """ @@ -398,16 +496,7 @@ async def delete(self, key: str) -> None: key : str The key to delete """ - await super().delete(key) - await self._invalidate_key(key) - - async def _invalidate_key(self, key: str) -> None: - """Drop every cached entry for `key`: its byte ranges, its full value, and its tracking.""" - async with self._state.lock: - self._invalidate_range_entries(key) - await self._cache.delete(key) - async with self._state.lock: - self._remove_from_tracking(key) + await self._write(key, super().delete(key), None) async def set_if_not_exists(self, key: str, value: Buffer) -> None: """ @@ -416,15 +505,14 @@ async def set_if_not_exists(self, key: str, value: Buffer) -> None: Whether the source store wrote `value` is not reported, so the cached entries for `key` are dropped either way; the next read fetches the source's value. """ - await super().set_if_not_exists(key, value) - await self._invalidate_key(key) + await self._write(key, super().set_if_not_exists(key, value), None) async def _set_many(self, values: Iterable[tuple[str, Buffer]]) -> None: """ Store each pair through `set`, so the cache sees every write. - Only the last value for a repeated key is written: concurrent `set` calls on one key - could otherwise leave the cache and the source holding different values. + Only the last value for a repeated key is written, so the source ends up holding it: + concurrent `set` calls on one key could leave either value there. """ await asyncio.gather(*starmap(self.set, dict(values).items())) @@ -447,23 +535,20 @@ def delete_sync(self, key: str) -> None: raise TypeError(f"{type(self).__name__} does not support synchronous delete.") async def clear(self) -> None: - """Clear the source store and both caches.""" + """Clear the source store and both caches. + + If clearing the source raises, the caches are left as they were. + """ await super().clear() - await self.clear_cache() + await asyncio.shield(self._settle_clear()) async def delete_dir(self, prefix: str) -> None: - """Delete a source directory and invalidate its cached entries.""" + """Delete a source directory and invalidate its cached entries. + + If deleting from the source raises, the caches are left as they were. + """ await super().delete_dir(prefix) - await self._cache.delete_dir(prefix) - if prefix != "" and not prefix.endswith("/"): - prefix += "/" - async with self._state.lock: - for key in list(self._state.range_cache): - if key.startswith(prefix): - self._invalidate_range_entries(key) - for entry_key in list(self._state.key_sizes): - if isinstance(entry_key, str) and entry_key.startswith(prefix): - self._remove_from_tracking(entry_key) + await asyncio.shield(self._settle_delete_dir(prefix)) def cache_info(self) -> dict[str, Any]: """Return information about the cache state.""" @@ -493,17 +578,8 @@ def cache_stats(self) -> dict[str, Any]: async def clear_cache(self) -> None: """Clear all cached data and tracking information.""" - # Clear the cache store if it supports clear - if hasattr(self._cache, "clear"): - await self._cache.clear() - - # Reset tracking async with self._state.lock: - self._state.key_insert_times.clear() - self._state.cache_order.clear() - self._state.key_sizes.clear() - self._state.range_cache.clear() - self._state.current_size = 0 + await self._reset_cache() def __repr__(self) -> str: """Return string representation of the cache store.""" diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py index 38c25157df..b5068279d1 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -3,19 +3,31 @@ """ import asyncio +import random import time -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, MutableMapping from pathlib import Path from types import FunctionType -from typing import Literal +from typing import Any, Literal +import hypothesis.strategies as st import numpy as np import pytest +from hypothesis import settings +from hypothesis.stateful import RuleBasedStateMachine, initialize, invariant, rule import zarr -from zarr.abc.store import RangeByteRequest, Store, SuffixByteRequest +from zarr.abc.store import ( + ByteRequest, + OffsetByteRequest, + RangeByteRequest, + Store, + SuffixByteRequest, +) +from zarr.core.buffer import Buffer, BufferPrototype from zarr.core.buffer.core import default_buffer_prototype from zarr.core.buffer.cpu import Buffer as CPUBuffer +from zarr.core.sync import sync from zarr.experimental.cache_store import CacheStore from zarr.storage import LocalStore, MemoryStore from zarr.storage._wrapper import WrapperStore @@ -698,8 +710,8 @@ async def test_get_no_cache_delete_tracking(self) -> None: # First, add key to cache tracking but not to source test_data = CPUBuffer.from_bytes(b"test data") - await cache_store.set("phantom_key", test_data) - await cached_store._track_entry("phantom_key", test_data) + async with cached_store._state.lock: + await cached_store._install_entry("phantom_key", test_data) # Verify it's in tracking assert "phantom_key" in cached_store._state.cache_order @@ -1445,3 +1457,370 @@ async def test_concurrent_reads_tolerate_eviction() -> None: assert [result.to_bytes() for result in results if result is not None] == [b"xxxx", b"xxxx"] _assert_size_accounting(cached) + + +class _PausingReadStore(MemoryStore): + """A `MemoryStore` whose reads pause after fetching their value, until `resume` is set.""" + + def __init__(self) -> None: + super().__init__() + self.fetched = asyncio.Event() + self.resume = asyncio.Event() + + async def get( + self, + key: str, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + result = await super().get(key, prototype, byte_range) + self.fetched.set() + await self.resume.wait() + return result + + +class _PausingWriteStore(MemoryStore): + """A `MemoryStore` whose writes of `pause_value` pause after writing, until `resume` is set.""" + + def __init__(self, pause_value: bytes) -> None: + super().__init__() + self.pause_value = pause_value + self.written = asyncio.Event() + self.resume = asyncio.Event() + + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: + await super().set(key, value, byte_range) + if value.to_bytes() == self.pause_value: + self.written.set() + await self.resume.wait() + + +async def _assert_reads_match_source(cached: CacheStore, key: str) -> None: + """Every read of `key` through `cached` returns the source's current value.""" + proto = default_buffer_prototype() + for byte_range in [None, RangeByteRequest(0, 3)]: + result = await cached.get(key, proto, byte_range) + expected = await cached._store.get(key, proto, byte_range) + assert (result is None) == (expected is None) + if result is not None and expected is not None: + assert result.to_bytes() == expected.to_bytes() + + +_cache_writes = pytest.mark.parametrize( + "write", + [ + lambda cached: cached.set("d/k", CPUBuffer.from_bytes(b"new value")), + lambda cached: cached.delete("d/k"), + lambda cached: cached.delete_dir("d"), + lambda cached: cached.clear(), + ], + ids=["set", "delete", "delete_dir", "clear"], +) + + +@_cache_writes +@pytest.mark.parametrize("byte_range", [None, RangeByteRequest(0, 3)]) +@pytest.mark.parametrize("cache_set_data", [True, False]) +async def test_read_miss_racing_a_write_does_not_cache_the_old_value( + write: Callable[[CacheStore], Awaitable[None]], + byte_range: ByteRequest | None, + cache_set_data: bool, +) -> None: + """ + A read that fetched a value before a write to the same key completed does not cache that + value once the write has replaced it. + """ + source = _PausingReadStore() + await source.set("d/k", CPUBuffer.from_bytes(b"old value")) + cached = CacheStore(source, cache_store=MemoryStore(), cache_set_data=cache_set_data) + read = asyncio.create_task(cached.get("d/k", default_buffer_prototype(), byte_range)) + await source.fetched.wait() + + await write(cached) + source.resume.set() + await read + + await _assert_reads_match_source(cached, "d/k") + _assert_size_accounting(cached) + + +async def test_overlapping_writes_leave_the_cache_matching_the_source() -> None: + """ + When two writes to one key overlap, the cache does not keep the value of the write that + reached the source first. + """ + source = _PausingWriteStore(pause_value=b"first value") + cache = MemoryStore() + cached = CacheStore(source, cache_store=cache) + first = asyncio.create_task(cached.set("d/k", CPUBuffer.from_bytes(b"first value"))) + await source.written.wait() + + await cached.set("d/k", CPUBuffer.from_bytes(b"second value")) + source.resume.set() + await first + + assert (await source.get("d/k", default_buffer_prototype())) is not None + assert "d/k" not in cache._store_dict or cache._store_dict["d/k"].to_bytes() == b"second value" + await _assert_reads_match_source(cached, "d/k") + _assert_size_accounting(cached) + + +@_cache_writes +async def test_cancelled_write_still_updates_the_cache( + write: Callable[[CacheStore], Awaitable[None]], +) -> None: + """ + Cancelling a write after it reached the source, while it waits to update the cache, does + not leave the old value cached. + """ + source = MemoryStore() + cached = CacheStore(source, cache_store=MemoryStore()) + await cached.set("d/k", CPUBuffer.from_bytes(b"old value")) + snapshot = dict(source._store_dict) + async with cached._state.lock: + task = asyncio.ensure_future(write(cached)) + for _ in range(10): + await asyncio.sleep(0) + assert source._store_dict != snapshot + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + # Wait for the shielded cache update, which queued for the lock before this. + async with cached._state.lock: + pass + + await _assert_reads_match_source(cached, "d/k") + _assert_size_accounting(cached) + + +@pytest.mark.parametrize("arrival", ["set", "get", "get_range"]) +async def test_values_larger_than_max_size_are_not_cached(arrival: str) -> None: + """ + A value larger than `max_size` is not written to the cache store, and the entry it + replaces is dropped, whether the value arrives by a write or by a read miss. + """ + source = MemoryStore() + cache = MemoryStore() + cached = CacheStore(source, cache_store=cache, max_size=8) + proto = default_buffer_prototype() + await cached.set("k", CPUBuffer.from_bytes(b"small")) + big = CPUBuffer.from_bytes(b"larger than max_size") + match arrival: + case "set": + await cached.set("k", big) + case "get": + await cached.clear_cache() + await source.set("k", big) + await cached.get("k", proto) + case "get_range": + await cached.clear_cache() + await source.set("k", big) + await cached.get("k", proto, OffsetByteRequest(0)) + + assert cache._store_dict == {} + assert cached._state.range_cache == {} + assert cached.cache_info()["current_size"] == 0 + _assert_size_accounting(cached) + result = await cached.get("k", proto) + assert result is not None + assert result.to_bytes() == big.to_bytes() + + +class _YieldingStore(MemoryStore): + """ + A `MemoryStore` that yields to the event loop around every operation, as I/O-backed stores do. + + How many times it yields is drawn from `schedule`, so concurrent operations interleave in + varied orders. + """ + + def __init__( + self, + store_dict: MutableMapping[str, Buffer] | None = None, + *, + read_only: bool = False, + schedule: random.Random, + ) -> None: + super().__init__(store_dict, read_only=read_only) + self.schedule = schedule + + def with_read_only(self, read_only: bool = False) -> "_YieldingStore": + return type(self)(self._store_dict, read_only=read_only, schedule=self.schedule) + + async def _yield(self) -> None: + for _ in range(self.schedule.randint(0, 3)): + await asyncio.sleep(0) + + async def get( + self, + key: str, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + await self._yield() + result = await super().get(key, prototype, byte_range) + await self._yield() + return result + + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: + await self._yield() + await super().set(key, value, byte_range) + await self._yield() + + async def set_if_not_exists(self, key: str, value: Buffer) -> None: + await self._yield() + await super().set_if_not_exists(key, value) + await self._yield() + + async def delete(self, key: str) -> None: + await self._yield() + await super().delete(key) + await self._yield() + + async def clear(self) -> None: + await self._yield() + await super().clear() + await self._yield() + + +_SM_KEYS = ("a", "b", "d/x", "d/y", "e/z") +_SM_BYTE_RANGES = ( + None, + RangeByteRequest(0, 3), + RangeByteRequest(2, 9), + OffsetByteRequest(1), + SuffixByteRequest(4), +) +_SM_WRITES = frozenset({"set", "delete", "set_if_not_exists", "set_many", "delete_dir", "clear"}) +_sm_keys = st.sampled_from(_SM_KEYS) +_sm_values = st.binary(max_size=24) +# Each operation is `(through_read_only_view, (name, *arguments))`. +_sm_operations = st.tuples( + st.booleans(), + st.one_of( + st.tuples(st.just("set"), _sm_keys, _sm_values), + st.tuples(st.just("get"), _sm_keys, st.sampled_from(_SM_BYTE_RANGES)), + st.tuples(st.just("delete"), _sm_keys), + st.tuples(st.just("set_if_not_exists"), _sm_keys, _sm_values), + st.tuples(st.just("set_many"), st.lists(st.tuples(_sm_keys, _sm_values), max_size=3)), + st.tuples(st.just("delete_dir"), st.sampled_from(["", "d", "d/", "e", "a"])), + st.tuples(st.just("clear")), + st.tuples(st.just("clear_cache")), + ), +) + + +async def _apply_operation(store: CacheStore, operation: tuple[Any, ...]) -> Buffer | None: + """Run one drawn operation against `store`, returning what a `get` returned.""" + match operation: + case ("set", key, data): + await store.set(key, CPUBuffer.from_bytes(data)) + case ("get", key, byte_range): + return await store.get(key, default_buffer_prototype(), byte_range) + case ("delete", key): + await store.delete(key) + case ("set_if_not_exists", key, data): + await store.set_if_not_exists(key, CPUBuffer.from_bytes(data)) + case ("set_many", pairs): + await store._set_many([(key, CPUBuffer.from_bytes(data)) for key, data in pairs]) + case ("delete_dir", prefix): + await store.delete_dir(prefix) + case ("clear",): + await store.clear() + case ("clear_cache",): + await store.clear_cache() + return None + + +async def _apply_operations( + machine: "CacheStoreMachine", operations: list[tuple[bool, tuple[Any, ...]]] +) -> list[Buffer | BaseException | None]: + """Run `operations` concurrently, through the read-only view where drawn.""" + return await asyncio.gather( + *( + _apply_operation(machine.read_only if read_only else machine.cached, operation) + for read_only, operation in operations + ), + return_exceptions=True, + ) + + +class CacheStoreMachine(RuleBasedStateMachine): + """ + Drive a `CacheStore` through random sequences of reads and writes, some of them concurrent. + + After every step the cache's size and LRU tracking describe exactly what the cache holds, + and everything the cache holds equals the source's current value. + """ + + @initialize( + max_size=st.one_of(st.none(), st.integers(0, 48)), + cache_set_data=st.booleans(), + schedule=st.randoms(use_true_random=False), + ) + def create(self, max_size: int | None, cache_set_data: bool, schedule: random.Random) -> None: + self.source = _YieldingStore(schedule=schedule) + self.cache = _YieldingStore(schedule=schedule) + self.cached = CacheStore( + self.source, cache_store=self.cache, max_size=max_size, cache_set_data=cache_set_data + ) + self.read_only = self.cached.with_read_only(True) + + def _check_results( + self, + operations: list[tuple[bool, tuple[Any, ...]]], + results: list[Buffer | BaseException | None], + ) -> None: + """Only writes through the read-only view may fail, and only because it is read-only.""" + for (read_only, operation), result in zip(operations, results, strict=True): + if isinstance(result, BaseException): + if read_only and operation[0] in _SM_WRITES and isinstance(result, ValueError): + continue + raise result + + @rule(operation=_sm_operations) + def apply_one(self, operation: tuple[bool, tuple[Any, ...]]) -> None: + """Run one operation alone; a `get` returns the source's current value.""" + (result,) = sync(_apply_operations(self, [operation])) + self._check_results([operation], [result]) + _, (name, *arguments) = operation + if name == "get": + key, byte_range = arguments + expected = sync(self.source.get(key, default_buffer_prototype(), byte_range)) + assert isinstance(result, Buffer | None) + assert (result is None) == (expected is None) + if result is not None and expected is not None: + assert result.to_bytes() == expected.to_bytes() + + @rule(operations=st.lists(_sm_operations, min_size=2, max_size=4)) + def apply_concurrently(self, operations: list[tuple[bool, tuple[Any, ...]]]) -> None: + """Run operations concurrently, so their awaits interleave.""" + self._check_results(operations, sync(_apply_operations(self, operations))) + + @invariant() + def tracking_matches_cache(self) -> None: + state = self.cached._state + assert state.current_size == sum(state.key_sizes.values()) + assert set(state.key_sizes) == set(state.cache_order) == set(state.key_insert_times) + if self.cached.max_size is not None: + assert state.current_size <= self.cached.max_size + tracked_keys = {key for key in state.key_sizes if isinstance(key, str)} + assert set(self.cache._store_dict) == tracked_keys + tracked_ranges = {key for key in state.key_sizes if isinstance(key, tuple)} + assert { + (key, byte_range) for key, ranges in state.range_cache.items() for byte_range in ranges + } == tracked_ranges + for key in tracked_keys: + value = self.cache._store_dict[key].to_bytes() + assert state.key_sizes[key] == len(value) + assert value == self.source._store_dict[key].to_bytes() + for key, byte_range in tracked_ranges: + value = state.range_cache[key][byte_range].to_bytes() + expected = sync(self.source.get(key, default_buffer_prototype(), byte_range)) + assert state.key_sizes[(key, byte_range)] == len(value) + assert expected is not None + assert value == expected.to_bytes() + + +TestCacheStoreMachine = CacheStoreMachine.TestCase +TestCacheStoreMachine.settings = settings(max_examples=300, stateful_step_count=20, deadline=None) From 7d300802ee18e6ac9fb4fc93e5a39cc340807df6 Mon Sep 17 00:00:00 2001 From: Davis Bennett Date: Fri, 4 Dec 2026 14:18:46 +0100 Subject: [PATCH 03/12] fix(sharding): keep whole-shard reads in the buffer's own memory (#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/zarr-python#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 --- changes/4669.bugfix.md | 4 +++ src/zarr/codecs/bytes.py | 32 ++++++++++-------- src/zarr/codecs/sharding.py | 34 ++++++------------- tests/test_buffer.py | 34 +++++++++++++++++++ tests/test_codecs/test_sharding_unit.py | 44 ++++++++++++++----------- tests/test_fastpath_equivalence.py | 20 +++++++---- 6 files changed, 105 insertions(+), 63 deletions(-) create mode 100644 changes/4669.bugfix.md diff --git a/changes/4669.bugfix.md b/changes/4669.bugfix.md new file mode 100644 index 0000000000..8cc20a4fa8 --- /dev/null +++ b/changes/4669.bugfix.md @@ -0,0 +1,4 @@ +Reading an uncompressed sharded array into GPU memory with `FusedCodecPipeline` +no longer raises `ValueError: non-scalar numpy.ndarray cannot be used for fill`. +Under `FusedCodecPipeline`, whole uncompressed shards with structured data types +now also take the fast path. diff --git a/src/zarr/codecs/bytes.py b/src/zarr/codecs/bytes.py index 9ebcaa4c02..c32206f32b 100644 --- a/src/zarr/codecs/bytes.py +++ b/src/zarr/codecs/bytes.py @@ -21,6 +21,7 @@ from zarr.abc.store import ByteGetter from zarr.core.array_spec import ArraySpec from zarr.core.buffer import Buffer, NDBuffer + from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType from zarr.core.indexing import Selector, SelectorTuple @@ -100,25 +101,30 @@ def evolve_from_array_spec(self, array_spec: ArraySpec) -> Self: ) return self + def _stored_dtype(self, dtype: ZDType[TBaseDType, TBaseScalar]) -> np.dtype[Any]: + """The NumPy data type to view stored bytes with. + + The byte order of the stored data is set by this codec's `endian` + configuration; the byte order of the decoded array is set by the array's + data type. The two are independent: the raw bytes are viewed with a dtype + in the stored byte order, then converted to the declared dtype if needed. + """ + if isinstance(dtype, HasEndianness): + return replace(dtype, endianness=self.endian).to_native_dtype() # type: ignore[call-arg] + native = dtype.to_native_dtype() + if isinstance(dtype, Struct) and self.endian is not None: + # Per the struct data type spec, all multi-byte fields are stored in the + # byte order configured on this codec. + return native.newbyteorder(self.endian) + return native + def _decode_sync( self, chunk_bytes: Buffer, chunk_spec: ArraySpec, ) -> NDBuffer: - endian_str = self.endian dtype = chunk_spec.dtype.to_native_dtype() - # The byte order of the stored data is set by this codec's `endian` - # configuration; the byte order of the decoded array is set by the array's - # data type. The two are independent: the raw bytes are viewed with a dtype - # in the stored byte order, then converted to the declared dtype if needed. - if isinstance(chunk_spec.dtype, HasEndianness): - view_dtype = replace(chunk_spec.dtype, endianness=endian_str).to_native_dtype() # type: ignore[call-arg] - elif isinstance(chunk_spec.dtype, Struct) and endian_str is not None: - # Per the struct data type spec, all multi-byte fields are stored in the - # byte order configured on this codec. - view_dtype = dtype.newbyteorder(endian_str) - else: - view_dtype = dtype + view_dtype = self._stored_dtype(chunk_spec.dtype) as_array_like = chunk_bytes.as_array_like() chunk_array = chunk_spec.prototype.nd_buffer.from_ndarray_like( as_array_like.view(dtype=view_dtype) # type: ignore[attr-defined] diff --git a/src/zarr/codecs/sharding.py b/src/zarr/codecs/sharding.py index d4ccf71cb9..f1823f533d 100644 --- a/src/zarr/codecs/sharding.py +++ b/src/zarr/codecs/sharding.py @@ -52,9 +52,7 @@ product, ) from zarr.core.config import config as zarr_config -from zarr.core.dtype.common import HasEndianness from zarr.core.dtype.npy.int import UInt64 -from zarr.core.dtype.npy.structured import Struct from zarr.core.indexing import ( BasicIndexer, ChunkProjection, @@ -1187,8 +1185,6 @@ def _decode_full_shard_bulk_if_uncompressed( dtype/endian view with no reordering. A trailing crc32c is NOT accepted (the bulk path can't verify per-chunk checksums, so crc shards keep the per-chunk path's corruption detection); - - the data type is not structured (the byte-order handling below has no - `Struct` branch); - `indexer` is an identity full-shard read (`_is_identity_full_read`); - the stored index is dense (every chunk present, equal fixed length, exactly tiling the data section) so the data section is a regular @@ -1197,7 +1193,8 @@ def _decode_full_shard_bulk_if_uncompressed( Chunk positions are read from the stored index, so this is correct for any `subchunk_write_order` (morton / lexicographic / colexicographic / unordered). The on-disk byte order is taken from the BytesCodec's - `endian`, so big- and little-endian shards both decode correctly. + `endian` (`BytesCodec._stored_dtype`), so big- and little-endian shards, + structured ones included, decode as they do on the per-chunk path. """ # --- gate on a trivial, fixed-size inner codec chain --- if not self._inner_codecs_fixed_size: @@ -1212,12 +1209,6 @@ def _decode_full_shard_bulk_if_uncompressed( return None ab_codec = self.codecs[0] - # The byte-order handling below lacks the structured-dtype branch of - # `BytesCodec._decode_sync` (which applies `newbyteorder` to multi-byte - # struct fields), so structured dtypes must take the per-chunk path. - if isinstance(shard_spec.dtype, Struct): - return None - chunks_per_shard = self._get_chunks_per_shard(shard_spec) chunk_spec = self._get_chunk_spec(shard_spec) n_chunks = product(chunks_per_shard) @@ -1257,21 +1248,16 @@ def _decode_full_shard_bulk_if_uncompressed( # a dense, crc-free, fixed-size layout the payload length is exactly the # encoded item-bytes of one chunk. native_dtype = shard_spec.dtype.to_native_dtype() - raw = shard_bytes.as_numpy_array().view(np.uint8) + # `as_array_like`, not `as_numpy_array`: the payloads must stay in the + # buffer's own memory (a CuPy array under `zarr.config.enable_gpu()`), or + # assigning them into a device `out` below fails. + raw = shard_bytes.as_array_like() payload = chunk_byte_length cs = self.chunk_shape - # On-disk byte order is carried by the BytesCodec's `endian`, NOT by the - # data type (zarr v3). Build the read-view dtype from the codec's endian - # exactly as BytesCodec._decode_sync does, so a big-endian shard read on a - # little-endian host (or vice versa) is interpreted correctly. Assigning - # into the native-dtype `out` then performs any needed byteswap. `endian` - # is now a plain Literal['little', 'big'] | None string (no longer an enum). - endian_str = ab_codec.endian - if isinstance(chunk_spec.dtype, HasEndianness): - stored_dtype = replace(chunk_spec.dtype, endianness=endian_str).to_native_dtype() # type: ignore[call-arg] - else: - stored_dtype = chunk_spec.dtype.to_native_dtype() + # data type (zarr v3). Assigning the stored-order view into the + # native-dtype `out` performs any needed byteswap. + stored_dtype = ab_codec._stored_dtype(chunk_spec.dtype) offsets = index.offsets_and_lengths[..., 0].reshape(-1) # localized coords, C-order coords_c = list(np.ndindex(chunks_per_shard)) @@ -1280,7 +1266,7 @@ def _decode_full_shard_bulk_if_uncompressed( ) for flat, coord in enumerate(coords_c): start = int(offsets[flat]) - chunk = raw[start : start + payload].view(stored_dtype).reshape(cs) + chunk = raw[start : start + payload].view(stored_dtype).reshape(cs) # type: ignore[attr-defined] sel = tuple(slice(c * s, c * s + s) for c, s in zip(coord, cs, strict=True)) out[sel] = chunk return out diff --git a/tests/test_buffer.py b/tests/test_buffer.py index 307abfe499..037cca3d6e 100644 --- a/tests/test_buffer.py +++ b/tests/test_buffer.py @@ -179,6 +179,40 @@ async def test_sharding_use_of_gpu_prototype() -> None: assert cp.array_equal(expect, got) +@gpu_test +@pytest.mark.filterwarnings( + "ignore:Creating a zarr.buffer.gpu.Buffer with an array that does not support:zarr.errors.ZarrUserWarning" +) +@pytest.mark.parametrize( + "pipeline", + [ + "zarr.core.codec_pipeline.BatchedCodecPipeline", + "zarr.core.codec_pipeline.FusedCodecPipeline", + ], +) +@pytest.mark.parametrize("compressors", [None, "auto"]) +def test_read_sharded_array_into_gpu_memory( + pipeline: str, compressors: Literal["auto"] | None +) -> None: + """Both codec pipelines read sharded arrays, compressed or not, into CuPy arrays. + + The uncompressed case takes the sharding codec's whole-shard fast path, which + once copied each shard to host memory and then failed to assign it into the + device output (zarr-developers/zarr-python#4654). + """ + store = MemoryStore() + z = zarr.create_array( + store, shape=(100,), chunks=(10,), shards=(50,), dtype="int32", compressors=compressors + ) + z[:] = np.arange(100, dtype="int32") + + with zarr.config.enable_gpu(), zarr.config.set({"codec_pipeline.path": pipeline}): + got = zarr.open_array(store, mode="r")[:] + + assert isinstance(got, cp.ndarray) + assert cp.array_equal(got, cp.arange(100, dtype="int32")) + + def test_numpy_buffer_prototype() -> None: buffer = cpu.buffer_prototype.buffer.create_zero_length() ndbuffer = cpu.buffer_prototype.nd_buffer.create(shape=(1, 2), dtype=np.dtype("int64")) diff --git a/tests/test_codecs/test_sharding_unit.py b/tests/test_codecs/test_sharding_unit.py index 978f7882f4..f27e0cd49a 100644 --- a/tests/test_codecs/test_sharding_unit.py +++ b/tests/test_codecs/test_sharding_unit.py @@ -1070,29 +1070,33 @@ def _spec_for(data: np.ndarray[Any, np.dtype[Any]]) -> ArraySpec: ) -def test_bulk_decode_declines_structured_dtype() -> None: - """The bulk path has no structured-dtype byte-order handling (the `Struct` - branch of `BytesCodec._decode_sync`), so it must decline structured specs. - The plain-dtype control on an identically constructed blob proves the - decline comes from the dtype gate, not from a malformed blob.""" - codec = ShardingCodec(chunk_shape=(2,), codecs=[BytesCodec(endian="little")]) - - # control: same construction with a plain dtype engages the bulk path - plain = np.arange(4, dtype=" None: + """The bulk path views each payload with `BytesCodec._stored_dtype`, the same + data type the per-chunk path uses, so plain and structured shards decode + correctly whichever byte order the codec stored them in.""" + codec = ShardingCodec(chunk_shape=(2,), codecs=[BytesCodec(endian=endian)]) + data = np.zeros(4, dtype=dtype) + if dtype.names is None: + data[:] = np.arange(4) + else: + data["a"] = np.arange(4) + data["b"] = np.arange(4) * 0.5 + stored = data.astype(dtype.newbyteorder(endian)) - struct_data = np.zeros(4, dtype=np.dtype([("a", "u2"), ("c", "u1")])), +) -def _spec(shape: tuple[int, ...], dtype: str, *, write_empty_chunks: bool = True) -> ArraySpec: +def _spec( + shape: tuple[int, ...], dtype: str | np.dtype[Any], *, write_empty_chunks: bool = True +) -> ArraySpec: zdtype = get_data_type_from_native_dtype(np.dtype(dtype)) return ArraySpec( shape=shape, @@ -110,8 +118,7 @@ def _shard_cases(draw: st.DrawFn) -> dict[str, Any]: chunk_shape = tuple(draw(st.integers(1, 4)) for _ in range(ndim)) grid = tuple(draw(st.integers(1, 3)) for _ in range(ndim)) shard_shape = tuple(c * g for c, g in zip(chunk_shape, grid, strict=True)) - dtype = draw(_DTYPES) - data = draw(npst.arrays(dtype=np.dtype(dtype), shape=shard_shape)) + data = draw(npst.arrays(dtype=draw(_BULK_DTYPES), shape=shard_shape)) return { "chunk_shape": chunk_shape, "shard_shape": shard_shape, @@ -128,15 +135,16 @@ def _shard_cases(draw: st.DrawFn) -> dict[str, Any]: @given(case=_shard_cases()) def test_bulk_shard_decode_equals_general_decode(case: dict[str, Any]) -> None: """For dense fixed-size uncompressed shards, the vectorized bulk decode must - reproduce the general per-chunk decode exactly, whatever the endianness, - subchunk write order, or index location.""" + reproduce the general per-chunk decode exactly, whatever the data type + (structured ones included), endianness, subchunk write order, or index + location.""" codec = ShardingCodec( chunk_shape=case["chunk_shape"], codecs=[BytesCodec(endian=case["endian"])], index_location=case["index_location"], subchunk_write_order=case["subchunk_write_order"], ) - spec = _spec(case["shard_shape"], str(case["data"].dtype), write_empty_chunks=True) + spec = _spec(case["shard_shape"], case["data"].dtype, write_empty_chunks=True) blob = codec._encode_sync(CPUNDBuffer.from_numpy_array(case["data"]), spec) assert blob is not None # write_empty_chunks=True -> dense, never elided From 2d08a7edcc2b6a81037c186e5f31a2671e77c8aa Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 14:19:49 +0100 Subject: [PATCH 04/12] fix(experimental): drop CacheStore entries when a write is cancelled 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 --- src/zarr/experimental/cache_store.py | 52 ++++++++++------ tests/test_experimental/test_cache_store.py | 66 ++++++++++++++------- 2 files changed, 79 insertions(+), 39 deletions(-) diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index 38d3ab2bf6..2c21bd5298 100644 --- a/src/zarr/experimental/cache_store.py +++ b/src/zarr/experimental/cache_store.py @@ -210,17 +210,17 @@ async def _install_entry(self, entry_key: _CacheEntryKey, value: Buffer) -> None return # Release the old entry first, so making room counts only the other entries. self._remove_from_tracking(entry_key) - await self._accommodate_value(value_size) - if isinstance(entry_key, str): - try: + try: + await self._accommodate_value(value_size) + if isinstance(entry_key, str): await self._cache.set(entry_key, value) - except BaseException: - # The write may have left the old value behind, untracked. - await self._cache.delete(entry_key) - raise - else: - base_key, byte_range = entry_key - self._state.range_cache.setdefault(base_key, {})[byte_range] = value + else: + base_key, byte_range = entry_key + self._state.range_cache.setdefault(base_key, {})[byte_range] = value + except BaseException: + # A failed eviction or write can leave the replaced value behind, untracked. + await self._drop_entry(entry_key) + raise self._state.cache_order[entry_key] = None self._state.current_size += value_size self._state.key_sizes[entry_key] = value_size @@ -282,12 +282,12 @@ async def _reset_cache(self) -> None: Must be called while holding self._state.lock. """ - await self._cache.clear() self._state.key_insert_times.clear() self._state.cache_order.clear() self._state.key_sizes.clear() self._state.range_cache.clear() self._state.current_size = 0 + await self._cache.clear() # ------------------------------------------------------------------ # source operations in flight @@ -335,13 +335,16 @@ async def _write( """Run `write`, a write of `key` to the source store, then settle the cache for it. A write that raises is taken to have left the source unchanged, so the cache is left - as it was. Once the write succeeded, settling is shielded from cancellation: the - cache must follow the source even if the caller is cancelled while waiting for the - lock. + as it was. A cancelled write may still have reached the source, so its entry is + dropped. Settling is shielded from cancellation: the cache must follow the source + even if the caller is cancelled while waiting for the lock. """ op = self._begin(key) try: await write + except asyncio.CancelledError: + await asyncio.shield(self._settle_write(op, None)) + raise except BaseException: self._end(op) raise @@ -372,12 +375,12 @@ async def _settle_delete_dir(self, prefix: str) -> None: async with self._state.lock: for key in [key for key in self._state.pending if key.startswith(prefix)]: self._supersede(key) - await self._cache.delete_dir(prefix) for key in [key for key in self._state.range_cache if key.startswith(prefix)]: self._invalidate_range_entries(key) for entry_key in list(self._state.key_sizes): if isinstance(entry_key, str) and entry_key.startswith(prefix): self._remove_from_tracking(entry_key) + await self._cache.delete_dir(prefix) async def _settle_clear(self) -> None: """Drop every cache entry after a source `clear`.""" @@ -537,17 +540,28 @@ def delete_sync(self, key: str) -> None: async def clear(self) -> None: """Clear the source store and both caches. - If clearing the source raises, the caches are left as they were. + If clearing the source raises, the caches are left as they were. If the caller is + cancelled, the caches are cleared anyway, since the source may have been. """ - await super().clear() + try: + await super().clear() + except asyncio.CancelledError: + await asyncio.shield(self._settle_clear()) + raise await asyncio.shield(self._settle_clear()) async def delete_dir(self, prefix: str) -> None: """Delete a source directory and invalidate its cached entries. - If deleting from the source raises, the caches are left as they were. + If deleting from the source raises, the caches are left as they were. If the caller + is cancelled, the entries are invalidated anyway, since the source may have deleted + them. """ - await super().delete_dir(prefix) + try: + await super().delete_dir(prefix) + except asyncio.CancelledError: + await asyncio.shield(self._settle_delete_dir(prefix)) + raise await asyncio.shield(self._settle_delete_dir(prefix)) def cache_info(self) -> dict[str, Any]: diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py index b5068279d1..961371c44a 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -1480,20 +1480,34 @@ async def get( class _PausingWriteStore(MemoryStore): - """A `MemoryStore` whose writes of `pause_value` pause after writing, until `resume` is set.""" + """ + A `MemoryStore` whose writes, while `pause` is true, pause after changing the store until + `resume` is set. + """ - def __init__(self, pause_value: bytes) -> None: + def __init__(self) -> None: super().__init__() - self.pause_value = pause_value + self.pause = False self.written = asyncio.Event() self.resume = asyncio.Event() - async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: - await super().set(key, value, byte_range) - if value.to_bytes() == self.pause_value: + async def _pause_after_write(self) -> None: + if self.pause: self.written.set() await self.resume.wait() + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: + await super().set(key, value, byte_range) + await self._pause_after_write() + + async def delete(self, key: str) -> None: + await super().delete(key) + await self._pause_after_write() + + async def clear(self) -> None: + await super().clear() + await self._pause_after_write() + async def _assert_reads_match_source(cached: CacheStore, key: str) -> None: """Every read of `key` through `cached` returns the source's current value.""" @@ -1549,11 +1563,13 @@ async def test_overlapping_writes_leave_the_cache_matching_the_source() -> None: When two writes to one key overlap, the cache does not keep the value of the write that reached the source first. """ - source = _PausingWriteStore(pause_value=b"first value") + source = _PausingWriteStore() cache = MemoryStore() cached = CacheStore(source, cache_store=cache) + source.pause = True first = asyncio.create_task(cached.set("d/k", CPUBuffer.from_bytes(b"first value"))) await source.written.wait() + source.pause = False await cached.set("d/k", CPUBuffer.from_bytes(b"second value")) source.resume.set() @@ -1566,25 +1582,35 @@ async def test_overlapping_writes_leave_the_cache_matching_the_source() -> None: @_cache_writes +@pytest.mark.parametrize("cancelled_while", ["writing_source", "waiting_for_lock"]) async def test_cancelled_write_still_updates_the_cache( - write: Callable[[CacheStore], Awaitable[None]], + write: Callable[[CacheStore], Awaitable[None]], cancelled_while: str ) -> None: """ - Cancelling a write after it reached the source, while it waits to update the cache, does - not leave the old value cached. + Cancelling a write after it changed the source, either before the source call returned or + while the write waits to update the cache, does not leave the old value cached. """ - source = MemoryStore() + source = _PausingWriteStore() cached = CacheStore(source, cache_store=MemoryStore()) await cached.set("d/k", CPUBuffer.from_bytes(b"old value")) - snapshot = dict(source._store_dict) - async with cached._state.lock: - task = asyncio.ensure_future(write(cached)) - for _ in range(10): - await asyncio.sleep(0) - assert source._store_dict != snapshot - task.cancel() - with pytest.raises(asyncio.CancelledError): - await task + match cancelled_while: + case "writing_source": + source.pause = True + task = asyncio.ensure_future(write(cached)) + await source.written.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + case "waiting_for_lock": + snapshot = dict(source._store_dict) + async with cached._state.lock: + task = asyncio.ensure_future(write(cached)) + for _ in range(10): + await asyncio.sleep(0) + assert source._store_dict != snapshot + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task # Wait for the shielded cache update, which queued for the lock before this. async with cached._state.lock: pass From c321e9ec7128f8aa920b152d36ba204aefde19d5 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 14:58:58 +0100 Subject: [PATCH 05/12] fix(experimental): drop CacheStore entries a failed source write removed `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 --- src/zarr/experimental/cache_store.py | 52 +++-- tests/test_experimental/test_cache_store.py | 229 ++++++++++++++++---- 2 files changed, 225 insertions(+), 56 deletions(-) diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index 2c21bd5298..bfc792b9f1 100644 --- a/src/zarr/experimental/cache_store.py +++ b/src/zarr/experimental/cache_store.py @@ -334,19 +334,15 @@ async def _write( ) -> None: """Run `write`, a write of `key` to the source store, then settle the cache for it. - A write that raises is taken to have left the source unchanged, so the cache is left - as it was. A cancelled write may still have reached the source, so its entry is - dropped. Settling is shielded from cancellation: the cache must follow the source - even if the caller is cancelled while waiting for the lock. + A write that raises or is cancelled may still have reached the source, so the key's + entry is dropped. Settling is shielded from cancellation: the cache must follow the + source even if the caller is cancelled while waiting for the lock. """ op = self._begin(key) try: await write - except asyncio.CancelledError: - await asyncio.shield(self._settle_write(op, None)) - raise except BaseException: - self._end(op) + await asyncio.shield(self._settle_write(op, None)) raise await asyncio.shield(self._settle_write(op, value)) @@ -382,6 +378,29 @@ async def _settle_delete_dir(self, prefix: str) -> None: self._remove_from_tracking(entry_key) await self._cache.delete_dir(prefix) + async def _settle_failed_delete_dir(self, prefix: str) -> None: + """Drop the cache entries under `prefix` whose keys a failed source deletion removed. + + `Store.delete_dir` and `clear` need not be atomic: one that raises may have deleted + some keys. Entries for keys the source still holds are kept. + """ + if prefix != "" and not prefix.endswith("/"): + prefix += "/" + async with self._state.lock: + # Pending keys too: a read in flight may have fetched a key that is now gone. + tracked = {key for key in self._state.key_sizes if isinstance(key, str)} + candidates = sorted( + key + for key in tracked.union(self._state.range_cache, self._state.pending) + if key.startswith(prefix) + ) + present = await asyncio.gather(*map(self._store.exists, candidates)) + for key, exists in zip(candidates, present, strict=True): + if not exists: + self._supersede(key) + self._invalidate_range_entries(key) + await self._drop_entry(key) + async def _settle_clear(self) -> None: """Drop every cache entry after a source `clear`.""" async with self._state.lock: @@ -540,28 +559,35 @@ def delete_sync(self, key: str) -> None: async def clear(self) -> None: """Clear the source store and both caches. - If clearing the source raises, the caches are left as they were. If the caller is - cancelled, the caches are cleared anyway, since the source may have been. + If clearing the source raises, only the entries for keys the source no longer holds + are dropped. If the caller is cancelled, the caches are cleared anyway, since the + source may yet be. """ try: await super().clear() except asyncio.CancelledError: await asyncio.shield(self._settle_clear()) raise + except BaseException: + await asyncio.shield(self._settle_failed_delete_dir("")) + raise await asyncio.shield(self._settle_clear()) async def delete_dir(self, prefix: str) -> None: """Delete a source directory and invalidate its cached entries. - If deleting from the source raises, the caches are left as they were. If the caller - is cancelled, the entries are invalidated anyway, since the source may have deleted - them. + If deleting from the source raises, only the entries for keys the source no longer + holds are dropped. If the caller is cancelled, every entry under `prefix` is dropped, + since the source may yet delete them. """ try: await super().delete_dir(prefix) except asyncio.CancelledError: await asyncio.shield(self._settle_delete_dir(prefix)) raise + except BaseException: + await asyncio.shield(self._settle_failed_delete_dir(prefix)) + raise await asyncio.shield(self._settle_delete_dir(prefix)) def cache_info(self) -> dict[str, Any]: diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py index 961371c44a..b3d2f9670d 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -13,7 +13,6 @@ import hypothesis.strategies as st import numpy as np import pytest -from hypothesis import settings from hypothesis.stateful import RuleBasedStateMachine, initialize, invariant, rule import zarr @@ -1520,6 +1519,38 @@ async def _assert_reads_match_source(cached: CacheStore, key: str) -> None: assert result.to_bytes() == expected.to_bytes() +async def _assert_cache_coherent(cached: CacheStore) -> None: + """ + The cache's tracking describes exactly what it holds, and everything it holds equals the + source's current value. Both stores must be `MemoryStore`s. + """ + state = cached._state + cache = cached._cache + source = cached._store + assert isinstance(cache, MemoryStore) + assert isinstance(source, MemoryStore) + assert not state.pending, "a finished operation is still registered" + assert state.current_size == sum(state.key_sizes.values()) + assert set(state.key_sizes) == set(state.cache_order) == set(state.key_insert_times) + if cached.max_size is not None: + assert state.current_size <= cached.max_size + tracked_keys = {key for key in state.key_sizes if isinstance(key, str)} + assert set(cache._store_dict) == tracked_keys, "cache store and tracking disagree" + tracked_ranges = {key for key in state.key_sizes if isinstance(key, tuple)} + assert all(state.range_cache.values()), "empty per-key range dict left behind" + assert { + (key, byte_range) for key, ranges in state.range_cache.items() for byte_range in ranges + } == tracked_ranges + proto = default_buffer_prototype() + for entry_key in tracked_keys | tracked_ranges: + key, byte_range = (entry_key, None) if isinstance(entry_key, str) else entry_key + held = cache._store_dict[key] if byte_range is None else state.range_cache[key][byte_range] + expected = await source.get(key, proto, byte_range) + assert expected is not None, f"{entry_key!r} is cached but absent from the source" + assert state.key_sizes[entry_key] == len(held) + assert held.to_bytes() == expected.to_bytes(), f"{entry_key!r} is stale" + + _cache_writes = pytest.mark.parametrize( "write", [ @@ -1555,7 +1586,7 @@ async def test_read_miss_racing_a_write_does_not_cache_the_old_value( await read await _assert_reads_match_source(cached, "d/k") - _assert_size_accounting(cached) + await _assert_cache_coherent(cached) async def test_overlapping_writes_leave_the_cache_matching_the_source() -> None: @@ -1578,7 +1609,7 @@ async def test_overlapping_writes_leave_the_cache_matching_the_source() -> None: assert (await source.get("d/k", default_buffer_prototype())) is not None assert "d/k" not in cache._store_dict or cache._store_dict["d/k"].to_bytes() == b"second value" await _assert_reads_match_source(cached, "d/k") - _assert_size_accounting(cached) + await _assert_cache_coherent(cached) @_cache_writes @@ -1616,14 +1647,139 @@ async def test_cancelled_write_still_updates_the_cache( pass await _assert_reads_match_source(cached, "d/k") - _assert_size_accounting(cached) + await _assert_cache_coherent(cached) + + +async def test_read_settling_ahead_of_a_queued_write_is_replaced_by_it() -> None: + """ + A read whose cache update is queued for the lock ahead of a write's update to the same key + does not overwrite the write's update. + """ + source = MemoryStore() + await source.set("k", CPUBuffer.from_bytes(b"old value")) + cached = CacheStore(source, cache_store=MemoryStore()) + async with cached._state.lock: + read = asyncio.ensure_future(cached.get("k", default_buffer_prototype())) + for _ in range(10): + await asyncio.sleep(0) + write = asyncio.ensure_future(cached.set("k", CPUBuffer.from_bytes(b"new value"))) + for _ in range(10): + await asyncio.sleep(0) + assert source._store_dict["k"].to_bytes() == b"new value" + await asyncio.gather(read, write) + + await _assert_cache_coherent(cached) + + +async def test_cancelled_read_leaves_the_cache_coherent() -> None: + """A read cancelled while waiting to cache its value leaves no trace and no half update.""" + source = MemoryStore() + await source.set("k", CPUBuffer.from_bytes(b"value")) + cached = CacheStore(source, cache_store=MemoryStore()) + async with cached._state.lock: + read = asyncio.ensure_future(cached.get("k", default_buffer_prototype())) + for _ in range(10): + await asyncio.sleep(0) + read.cancel() + with pytest.raises(asyncio.CancelledError): + await read + async with cached._state.lock: + pass + + await _assert_cache_coherent(cached) + + +class _FailingCacheStore(MemoryStore): + """A cache `MemoryStore` whose next `set` or `delete` raises when `fail_next` names it.""" + + def __init__(self) -> None: + super().__init__() + self.fail_next: str | None = None + + def _maybe_fail(self, method: str) -> None: + if self.fail_next == method: + self.fail_next = None + raise OSError(f"cache {method} failed") + + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: + self._maybe_fail("set") + await super().set(key, value, byte_range) + + async def delete(self, key: str) -> None: + self._maybe_fail("delete") + await super().delete(key) + + +@pytest.mark.parametrize("failing", ["set", "delete"]) +async def test_cache_store_failure_does_not_leave_the_replaced_value(failing: str) -> None: + """ + When writing an entry to the cache store, or evicting another to make room for it, fails, + the value it was replacing is not served afterwards. + """ + source = MemoryStore() + cache = _FailingCacheStore() + cached = CacheStore(source, cache_store=cache, max_size=12) + await cached.set("other", CPUBuffer.from_bytes(b"other")) + await cached.set("k", CPUBuffer.from_bytes(b"old")) + cache.fail_next = failing + with pytest.raises(OSError, match=f"cache {failing} failed"): + await cached.set("k", CPUBuffer.from_bytes(b"new value")) + + await _assert_cache_coherent(cached) + await _assert_reads_match_source(cached, "k") + + +class _PartlyFailingDeleteStore(MemoryStore): + """A `MemoryStore` whose deletes, one key at a time, fail after the first one.""" + + def __init__(self) -> None: + super().__init__() + self.deletes = 0 + + async def delete(self, key: str) -> None: + self.deletes += 1 + if self.deletes > 1: + raise OSError("source deletion failed") + await super().delete(key) + + async def clear(self) -> None: + for key in sorted(self._store_dict): + await self.delete(key) + + +@pytest.mark.parametrize( + "deletion", + [lambda cached: cached.delete_dir("d"), lambda cached: cached.clear()], + ids=["delete_dir", "clear"], +) +async def test_partly_failed_deletion_drops_deleted_keys( + deletion: Callable[[CacheStore], Awaitable[None]], +) -> None: + """ + A source deletion that raises after deleting some keys leaves none of those keys cached, + and keeps the entries for keys the source still holds. + """ + source = _PartlyFailingDeleteStore() + cache = MemoryStore() + cached = CacheStore(source, cache_store=cache) + for key in ["d/x", "d/y"]: + await cached.set(key, CPUBuffer.from_bytes(key.encode() * 2)) + await cached.get(key, default_buffer_prototype(), RangeByteRequest(0, 3)) + with pytest.raises(OSError, match="source deletion failed"): + await deletion(cached) + + assert set(source._store_dict) == {"d/y"} + assert set(cache._store_dict) == {"d/y"} + await _assert_cache_coherent(cached) + for key in ["d/x", "d/y"]: + await _assert_reads_match_source(cached, key) @pytest.mark.parametrize("arrival", ["set", "get", "get_range"]) async def test_values_larger_than_max_size_are_not_cached(arrival: str) -> None: """ - A value larger than `max_size` is not written to the cache store, and the entry it - replaces is dropped, whether the value arrives by a write or by a read miss. + A value larger than `max_size` is not written to the cache store, whether it arrives by a + write or by a read miss. A write of one also drops the entry it replaces. """ source = MemoryStore() cache = MemoryStore() @@ -1645,8 +1801,7 @@ async def test_values_larger_than_max_size_are_not_cached(arrival: str) -> None: assert cache._store_dict == {} assert cached._state.range_cache == {} - assert cached.cache_info()["current_size"] == 0 - _assert_size_accounting(cached) + await _assert_cache_coherent(cached) result = await cached.get("k", proto) assert result is not None assert result.to_bytes() == big.to_bytes() @@ -1720,12 +1875,15 @@ async def clear(self) -> None: _SM_WRITES = frozenset({"set", "delete", "set_if_not_exists", "set_many", "delete_dir", "clear"}) _sm_keys = st.sampled_from(_SM_KEYS) _sm_values = st.binary(max_size=24) -# Each operation is `(through_read_only_view, (name, *arguments))`. +_sm_get = st.tuples(st.just("get"), _sm_keys, st.sampled_from(_SM_BYTE_RANGES)) +_sm_set = st.tuples(st.just("set"), _sm_keys, _sm_values) +# Each operation is `(through_read_only_view, (name, *arguments))`. Reads and writes are +# repeated so they outnumber the operations that empty the cache, and the cache fills up. _sm_operations = st.tuples( st.booleans(), st.one_of( - st.tuples(st.just("set"), _sm_keys, _sm_values), - st.tuples(st.just("get"), _sm_keys, st.sampled_from(_SM_BYTE_RANGES)), + *([_sm_get] * 5), + *([_sm_set] * 3), st.tuples(st.just("delete"), _sm_keys), st.tuples(st.just("set_if_not_exists"), _sm_keys, _sm_values), st.tuples(st.just("set_many"), st.lists(st.tuples(_sm_keys, _sm_values), max_size=3)), @@ -1780,7 +1938,7 @@ class CacheStoreMachine(RuleBasedStateMachine): """ @initialize( - max_size=st.one_of(st.none(), st.integers(0, 48)), + max_size=st.one_of(st.none(), st.integers(0, 48), st.integers(4, 12)), cache_set_data=st.booleans(), schedule=st.randoms(use_true_random=False), ) @@ -1799,6 +1957,9 @@ def _check_results( ) -> None: """Only writes through the read-only view may fail, and only because it is read-only.""" for (read_only, operation), result in zip(operations, results, strict=True): + if isinstance(result, BaseException) and not isinstance(result, Exception): + # Hypothesis stops an overrunning example from inside the store's `schedule`. + raise result if isinstance(result, BaseException): if read_only and operation[0] in _SM_WRITES and isinstance(result, ValueError): continue @@ -1809,14 +1970,17 @@ def apply_one(self, operation: tuple[bool, tuple[Any, ...]]) -> None: """Run one operation alone; a `get` returns the source's current value.""" (result,) = sync(_apply_operations(self, [operation])) self._check_results([operation], [result]) - _, (name, *arguments) = operation - if name == "get": - key, byte_range = arguments - expected = sync(self.source.get(key, default_buffer_prototype(), byte_range)) - assert isinstance(result, Buffer | None) - assert (result is None) == (expected is None) - if result is not None and expected is not None: - assert result.to_bytes() == expected.to_bytes() + read_only, (name, *arguments) = operation + match name, arguments: + case "get", [key, byte_range]: + expected = sync(self.source.get(key, default_buffer_prototype(), byte_range)) + assert isinstance(result, Buffer | None) + assert (result is None) == (expected is None) + if result is not None and expected is not None: + assert result.to_bytes() == expected.to_bytes() + case "set_many", [pairs] if not read_only: + for key, data in dict(pairs).items(): + assert self.source._store_dict[key].to_bytes() == data @rule(operations=st.lists(_sm_operations, min_size=2, max_size=4)) def apply_concurrently(self, operations: list[tuple[bool, tuple[Any, ...]]]) -> None: @@ -1824,29 +1988,8 @@ def apply_concurrently(self, operations: list[tuple[bool, tuple[Any, ...]]]) -> self._check_results(operations, sync(_apply_operations(self, operations))) @invariant() - def tracking_matches_cache(self) -> None: - state = self.cached._state - assert state.current_size == sum(state.key_sizes.values()) - assert set(state.key_sizes) == set(state.cache_order) == set(state.key_insert_times) - if self.cached.max_size is not None: - assert state.current_size <= self.cached.max_size - tracked_keys = {key for key in state.key_sizes if isinstance(key, str)} - assert set(self.cache._store_dict) == tracked_keys - tracked_ranges = {key for key in state.key_sizes if isinstance(key, tuple)} - assert { - (key, byte_range) for key, ranges in state.range_cache.items() for byte_range in ranges - } == tracked_ranges - for key in tracked_keys: - value = self.cache._store_dict[key].to_bytes() - assert state.key_sizes[key] == len(value) - assert value == self.source._store_dict[key].to_bytes() - for key, byte_range in tracked_ranges: - value = state.range_cache[key][byte_range].to_bytes() - expected = sync(self.source.get(key, default_buffer_prototype(), byte_range)) - assert state.key_sizes[(key, byte_range)] == len(value) - assert expected is not None - assert value == expected.to_bytes() + def cache_is_coherent(self) -> None: + sync(_assert_cache_coherent(self.cached)) TestCacheStoreMachine = CacheStoreMachine.TestCase -TestCacheStoreMachine.settings = settings(max_examples=300, stateful_step_count=20, deadline=None) From 8a49c6144fe2d6e123ae8a41ff7e7ec9fc8b3dd7 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 15:20:58 +0100 Subject: [PATCH 06/12] fix(experimental): settle the CacheStore cache when the source call ends 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 --- src/zarr/experimental/cache_store.py | 100 ++++++++++------ tests/test_experimental/test_cache_store.py | 125 ++++++++++++++------ 2 files changed, 154 insertions(+), 71 deletions(-) diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index bfc792b9f1..c0519e358d 100644 --- a/src/zarr/experimental/cache_store.py +++ b/src/zarr/experimental/cache_store.py @@ -231,9 +231,12 @@ async def _drop_entry(self, entry_key: _CacheEntryKey) -> None: For `str` keys the entry is deleted from the Store-backed cache, whether or not it is tracked. For `(str, ByteRequest)` keys it is removed from the in-memory range cache. + Tracking is released first, so the entry is no longer served even if the cache-store + delete fails. Must be called while holding self._state.lock. """ + self._remove_from_tracking(entry_key) if isinstance(entry_key, str): await self._cache.delete(entry_key) else: @@ -243,17 +246,16 @@ async def _drop_entry(self, entry_key: _CacheEntryKey) -> None: per_key.pop(byte_range, None) if not per_key: del self._state.range_cache[base_key] - self._remove_from_tracking(entry_key) async def _update_access_order(self, entry_key: _CacheEntryKey) -> None: """Update the access order for LRU tracking. - The membership check happens under the lock: another task can evict the entry while - this one waits for the lock. + This takes no lock: nothing is awaited between the membership check and the move, so + no other task can evict the entry in between, and hits need not queue behind cache + writes. """ - async with self._state.lock: - if entry_key in self._state.cache_order: - self._state.cache_order.move_to_end(entry_key) + if entry_key in self._state.cache_order: + self._state.cache_order.move_to_end(entry_key) def _remove_from_tracking(self, entry_key: _CacheEntryKey) -> None: """Remove an entry from all tracking structures and release its size. @@ -334,17 +336,24 @@ async def _write( ) -> None: """Run `write`, a write of `key` to the source store, then settle the cache for it. - A write that raises or is cancelled may still have reached the source, so the key's - entry is dropped. Settling is shielded from cancellation: the cache must follow the - source even if the caller is cancelled while waiting for the lock. + The write and its settling run as one task that cancelling the caller does not stop, + so the cache settles when the source write has really ended: a thread-backed store + keeps writing after its caller is cancelled. A write that raises may still have + reached the source, so the key's entry is dropped. """ + await asyncio.shield(self._write_and_settle(key, write, value)) + + async def _write_and_settle( + self, key: str, write: Coroutine[Any, Any, None], value: Buffer | None + ) -> None: + """The body of `_write`.""" op = self._begin(key) try: await write except BaseException: - await asyncio.shield(self._settle_write(op, None)) + await self._settle_write(op, None) raise - await asyncio.shield(self._settle_write(op, value)) + await self._settle_write(op, value) async def _settle_write(self, op: _PendingOp, value: Buffer | None) -> None: """Bring the cache in line with a completed source write of `op.key`. @@ -379,10 +388,11 @@ async def _settle_delete_dir(self, prefix: str) -> None: await self._cache.delete_dir(prefix) async def _settle_failed_delete_dir(self, prefix: str) -> None: - """Drop the cache entries under `prefix` whose keys a failed source deletion removed. + """Drop the cache entries under `prefix` whose keys a failed source deletion may have removed. `Store.delete_dir` and `clear` need not be atomic: one that raises may have deleted - some keys. Entries for keys the source still holds are kept. + some keys. Only entries for keys the source confirms it still holds are kept; if + asking the source fails, the entry is dropped. """ if prefix != "" and not prefix.endswith("/"): prefix += "/" @@ -394,9 +404,11 @@ async def _settle_failed_delete_dir(self, prefix: str) -> None: for key in tracked.union(self._state.range_cache, self._state.pending) if key.startswith(prefix) ) - present = await asyncio.gather(*map(self._store.exists, candidates)) + present = await asyncio.gather( + *map(self._store.exists, candidates), return_exceptions=True + ) for key, exists in zip(candidates, present, strict=True): - if not exists: + if exists is not True: self._supersede(key) self._invalidate_range_entries(key) await self._drop_entry(key) @@ -435,8 +447,14 @@ async def _get_try_cache( ) -> Buffer | None: """Try to get data from cache first, falling back to source store.""" if byte_range is None: - # Full-key read — use Store-backed cache - maybe_cached = await self._cache.get(key, prototype) + # Full-key read — use Store-backed cache. Only tracked keys are served: data the + # tracking does not describe (left by an earlier session, or by a failed cache-store + # delete) may be stale. + maybe_cached = ( + await self._cache.get(key, prototype) + if key in self._state.key_insert_times + else None + ) if maybe_cached is not None: self._state.hits += 1 await self._update_access_order(key) @@ -534,9 +552,15 @@ async def _set_many(self, values: Iterable[tuple[str, Buffer]]) -> None: Store each pair through `set`, so the cache sees every write. Only the last value for a repeated key is written, so the source ends up holding it: - concurrent `set` calls on one key could leave either value there. + concurrent `set` calls on one key could leave either value there. Every write ends + before this returns or raises the first write's error, so no write is left running. """ - await asyncio.gather(*starmap(self.set, dict(values).items())) + results = await asyncio.gather( + *starmap(self.set, dict(values).items()), return_exceptions=True + ) + for result in results: + if isinstance(result, BaseException): + raise result def set_sync(self, key: str, value: Buffer) -> None: """ @@ -559,36 +583,38 @@ def delete_sync(self, key: str) -> None: async def clear(self) -> None: """Clear the source store and both caches. - If clearing the source raises, only the entries for keys the source no longer holds - are dropped. If the caller is cancelled, the caches are cleared anyway, since the - source may yet be. + If clearing the source raises, the entries for keys the source may no longer hold are + dropped. Like `set`, the source call and the cache update run as one task that + cancelling the caller does not stop. """ + await asyncio.shield(self._clear_and_settle()) + + async def _clear_and_settle(self) -> None: + """The body of `clear`.""" try: await super().clear() - except asyncio.CancelledError: - await asyncio.shield(self._settle_clear()) - raise except BaseException: - await asyncio.shield(self._settle_failed_delete_dir("")) + await self._settle_failed_delete_dir("") raise - await asyncio.shield(self._settle_clear()) + await self._settle_clear() async def delete_dir(self, prefix: str) -> None: """Delete a source directory and invalidate its cached entries. - If deleting from the source raises, only the entries for keys the source no longer - holds are dropped. If the caller is cancelled, every entry under `prefix` is dropped, - since the source may yet delete them. + If deleting from the source raises, the entries for keys the source may no longer hold + are dropped. Like `set`, the source call and the cache update run as one task that + cancelling the caller does not stop. """ + await asyncio.shield(self._delete_dir_and_settle(prefix)) + + async def _delete_dir_and_settle(self, prefix: str) -> None: + """The body of `delete_dir`.""" try: await super().delete_dir(prefix) - except asyncio.CancelledError: - await asyncio.shield(self._settle_delete_dir(prefix)) - raise except BaseException: - await asyncio.shield(self._settle_failed_delete_dir(prefix)) + await self._settle_failed_delete_dir(prefix) raise - await asyncio.shield(self._settle_delete_dir(prefix)) + await self._settle_delete_dir(prefix) def cache_info(self) -> dict[str, Any]: """Return information about the cache state.""" @@ -618,6 +644,10 @@ def cache_stats(self) -> dict[str, Any]: async def clear_cache(self) -> None: """Clear all cached data and tracking information.""" + await asyncio.shield(self._clear_cache_locked()) + + async def _clear_cache_locked(self) -> None: + """The body of `clear_cache`.""" async with self._state.lock: await self._reset_cache() diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py index b3d2f9670d..4a65c75c2b 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -5,7 +5,7 @@ import asyncio import random import time -from collections.abc import Awaitable, Callable, MutableMapping +from collections.abc import Awaitable, Callable, Coroutine, MutableMapping from pathlib import Path from types import FunctionType from typing import Any, Literal @@ -1480,32 +1480,36 @@ async def get( class _PausingWriteStore(MemoryStore): """ - A `MemoryStore` whose writes, while `pause` is true, pause after changing the store until - `resume` is set. + A `MemoryStore` whose writes pause, `"before"` or `"after"` changing the store as `pause` + says, until `resume` is set. + + Like a store that writes in a thread, a write keeps running when its caller is cancelled. """ def __init__(self) -> None: super().__init__() - self.pause = False - self.written = asyncio.Event() + self.pause: Literal["never", "before", "after"] = "never" + self.paused = asyncio.Event() self.resume = asyncio.Event() - async def _pause_after_write(self) -> None: - if self.pause: - self.written.set() + async def _pause(self, when: Literal["before", "after"]) -> None: + if self.pause == when: + self.paused.set() await self.resume.wait() + async def _paused(self, write: Coroutine[Any, Any, None]) -> None: + await self._pause("before") + await write + await self._pause("after") + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: - await super().set(key, value, byte_range) - await self._pause_after_write() + await asyncio.shield(self._paused(super().set(key, value, byte_range))) async def delete(self, key: str) -> None: - await super().delete(key) - await self._pause_after_write() + await asyncio.shield(self._paused(super().delete(key))) async def clear(self) -> None: - await super().clear() - await self._pause_after_write() + await asyncio.shield(self._paused(super().clear())) async def _assert_reads_match_source(cached: CacheStore, key: str) -> None: @@ -1597,10 +1601,10 @@ async def test_overlapping_writes_leave_the_cache_matching_the_source() -> None: source = _PausingWriteStore() cache = MemoryStore() cached = CacheStore(source, cache_store=cache) - source.pause = True + source.pause = "after" first = asyncio.create_task(cached.set("d/k", CPUBuffer.from_bytes(b"first value"))) - await source.written.wait() - source.pause = False + await source.paused.wait() + source.pause = "never" await cached.set("d/k", CPUBuffer.from_bytes(b"second value")) source.resume.set() @@ -1613,25 +1617,32 @@ async def test_overlapping_writes_leave_the_cache_matching_the_source() -> None: @_cache_writes -@pytest.mark.parametrize("cancelled_while", ["writing_source", "waiting_for_lock"]) +@pytest.mark.parametrize("cancelled_while", ["source_call_running", "waiting_for_lock"]) async def test_cancelled_write_still_updates_the_cache( write: Callable[[CacheStore], Awaitable[None]], cancelled_while: str ) -> None: """ - Cancelling a write after it changed the source, either before the source call returned or - while the write waits to update the cache, does not leave the old value cached. + Cancelling a write's caller, either while the source call is still running or while the + write waits to update the cache, does not leave the old value cached once the source + call has landed. """ source = _PausingWriteStore() cached = CacheStore(source, cache_store=MemoryStore()) await cached.set("d/k", CPUBuffer.from_bytes(b"old value")) match cancelled_while: - case "writing_source": - source.pause = True + case "source_call_running": + # The source call keeps running after its caller is cancelled, as a thread does, + # and lands later. A read in between caches what the source holds until then. + source.pause = "before" task = asyncio.ensure_future(write(cached)) - await source.written.wait() + await source.paused.wait() task.cancel() with pytest.raises(asyncio.CancelledError): await task + await cached.get("d/k", default_buffer_prototype()) + source.resume.set() + for _ in range(10): + await asyncio.sleep(0) case "waiting_for_lock": snapshot = dict(source._store_dict) async with cached._state.lock: @@ -1710,11 +1721,22 @@ async def delete(self, key: str) -> None: await super().delete(key) -@pytest.mark.parametrize("failing", ["set", "delete"]) -async def test_cache_store_failure_does_not_leave_the_replaced_value(failing: str) -> None: +@pytest.mark.parametrize( + ("write", "failing"), + [ + (lambda cached: cached.set("k", CPUBuffer.from_bytes(b"new value")), "set"), + (lambda cached: cached.set("k", CPUBuffer.from_bytes(b"new value")), "delete"), + (lambda cached: cached.delete("k"), "delete"), + ], + ids=["set-cache_set_fails", "set-eviction_fails", "delete-cache_delete_fails"], +) +async def test_cache_store_failure_does_not_leave_the_replaced_value( + write: Callable[[CacheStore], Awaitable[None]], failing: str +) -> None: """ - When writing an entry to the cache store, or evicting another to make room for it, fails, - the value it was replacing is not served afterwards. + When the cache store fails while a write updates the cache (writing the new entry, + evicting another to make room for it, or deleting the old one), the value the write + replaced is not served afterwards. """ source = MemoryStore() cache = _FailingCacheStore() @@ -1723,18 +1745,31 @@ async def test_cache_store_failure_does_not_leave_the_replaced_value(failing: st await cached.set("k", CPUBuffer.from_bytes(b"old")) cache.fail_next = failing with pytest.raises(OSError, match=f"cache {failing} failed"): - await cached.set("k", CPUBuffer.from_bytes(b"new value")) + await write(cached) - await _assert_cache_coherent(cached) + # A failed cache-store delete may leave data behind, but untracked, so it is not served. + state = cached._state + assert state.current_size == sum(state.key_sizes.values()) + assert {key for key in state.key_sizes if isinstance(key, str)} <= set(cache._store_dict) await _assert_reads_match_source(cached, "k") + await _assert_reads_match_source(cached, "other") class _PartlyFailingDeleteStore(MemoryStore): - """A `MemoryStore` whose deletes, one key at a time, fail after the first one.""" + """ + A `MemoryStore` whose deletes, one key at a time, fail after the first one, and whose + `exists` fails while `exists_fails` is true. + """ - def __init__(self) -> None: + def __init__(self, *, exists_fails: bool) -> None: super().__init__() self.deletes = 0 + self.exists_fails = exists_fails + + async def exists(self, key: str) -> bool: + if self.exists_fails: + raise OSError("source unreachable") + return await super().exists(key) async def delete(self, key: str) -> None: self.deletes += 1 @@ -1752,14 +1787,16 @@ async def clear(self) -> None: [lambda cached: cached.delete_dir("d"), lambda cached: cached.clear()], ids=["delete_dir", "clear"], ) +@pytest.mark.parametrize("exists_fails", [False, True]) async def test_partly_failed_deletion_drops_deleted_keys( - deletion: Callable[[CacheStore], Awaitable[None]], + deletion: Callable[[CacheStore], Awaitable[None]], exists_fails: bool ) -> None: """ - A source deletion that raises after deleting some keys leaves none of those keys cached, - and keeps the entries for keys the source still holds. + A source deletion that raises after deleting some keys leaves none of those keys cached. + It keeps the entries for keys the source confirms it still holds, and drops them when + the source cannot say. """ - source = _PartlyFailingDeleteStore() + source = _PartlyFailingDeleteStore(exists_fails=exists_fails) cache = MemoryStore() cached = CacheStore(source, cache_store=cache) for key in ["d/x", "d/y"]: @@ -1768,13 +1805,29 @@ async def test_partly_failed_deletion_drops_deleted_keys( with pytest.raises(OSError, match="source deletion failed"): await deletion(cached) + source.exists_fails = False assert set(source._store_dict) == {"d/y"} - assert set(cache._store_dict) == {"d/y"} + assert set(cache._store_dict) == (set() if exists_fails else {"d/y"}) await _assert_cache_coherent(cached) for key in ["d/x", "d/y"]: await _assert_reads_match_source(cached, key) +async def test_untracked_cache_store_data_is_not_served() -> None: + """ + Data a cache store already holds without this `CacheStore` tracking it, such as a + persistent cache left by an earlier session, is not served: the source may have changed. + """ + source = MemoryStore() + cache = MemoryStore() + await cache.set("k", CPUBuffer.from_bytes(b"earlier value")) + await source.set("k", CPUBuffer.from_bytes(b"current value")) + cached = CacheStore(source, cache_store=cache) + + await _assert_reads_match_source(cached, "k") + await _assert_cache_coherent(cached) + + @pytest.mark.parametrize("arrival", ["set", "get", "get_range"]) async def test_values_larger_than_max_size_are_not_cached(arrival: str) -> None: """ From 52e58979dfb13dbff89de77cc164f2aa68b3fa24 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 15:47:01 +0100 Subject: [PATCH 07/12] test(experimental): cover CacheStore failed deletions racing reads 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 --- src/zarr/experimental/cache_store.py | 10 +- tests/test_experimental/test_cache_store.py | 216 ++++++++++++++++---- 2 files changed, 180 insertions(+), 46 deletions(-) diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index c0519e358d..14a469eb6b 100644 --- a/src/zarr/experimental/cache_store.py +++ b/src/zarr/experimental/cache_store.py @@ -336,9 +336,9 @@ async def _write( ) -> None: """Run `write`, a write of `key` to the source store, then settle the cache for it. - The write and its settling run as one task that cancelling the caller does not stop, + The write and its settling run as one task that canceling the caller does not stop, so the cache settles when the source write has really ended: a thread-backed store - keeps writing after its caller is cancelled. A write that raises may still have + keeps writing after its caller is canceled. A write that raises may still have reached the source, so the key's entry is dropped. """ await asyncio.shield(self._write_and_settle(key, write, value)) @@ -429,7 +429,7 @@ async def _fetch( ) -> Buffer | None: """Read from the source store and cache the result. - Like a write, settling is shielded from cancellation, so a cancelled read cannot leave + Like a write, settling is shielded from cancellation, so a canceled read cannot leave the cache half updated. """ self._state.misses += 1 @@ -585,7 +585,7 @@ async def clear(self) -> None: If clearing the source raises, the entries for keys the source may no longer hold are dropped. Like `set`, the source call and the cache update run as one task that - cancelling the caller does not stop. + canceling the caller does not stop. """ await asyncio.shield(self._clear_and_settle()) @@ -603,7 +603,7 @@ async def delete_dir(self, prefix: str) -> None: If deleting from the source raises, the entries for keys the source may no longer hold are dropped. Like `set`, the source call and the cache update run as one task that - cancelling the caller does not stop. + canceling the caller does not stop. """ await asyncio.shield(self._delete_dir_and_settle(prefix)) diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py index 4a65c75c2b..7c74e76ef0 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -1483,7 +1483,7 @@ class _PausingWriteStore(MemoryStore): A `MemoryStore` whose writes pause, `"before"` or `"after"` changing the store as `pause` says, until `resume` is set. - Like a store that writes in a thread, a write keeps running when its caller is cancelled. + Like a store that writes in a thread, a write keeps running when its caller is canceled. """ def __init__(self) -> None: @@ -1589,6 +1589,7 @@ async def test_read_miss_racing_a_write_does_not_cache_the_old_value( source.resume.set() await read + await _assert_cache_coherent(cached) await _assert_reads_match_source(cached, "d/k") await _assert_cache_coherent(cached) @@ -1612,26 +1613,27 @@ async def test_overlapping_writes_leave_the_cache_matching_the_source() -> None: assert (await source.get("d/k", default_buffer_prototype())) is not None assert "d/k" not in cache._store_dict or cache._store_dict["d/k"].to_bytes() == b"second value" + await _assert_cache_coherent(cached) await _assert_reads_match_source(cached, "d/k") await _assert_cache_coherent(cached) @_cache_writes -@pytest.mark.parametrize("cancelled_while", ["source_call_running", "waiting_for_lock"]) -async def test_cancelled_write_still_updates_the_cache( - write: Callable[[CacheStore], Awaitable[None]], cancelled_while: str +@pytest.mark.parametrize("canceled_while", ["source_call_running", "waiting_for_lock"]) +async def test_canceled_write_still_updates_the_cache( + write: Callable[[CacheStore], Awaitable[None]], canceled_while: str ) -> None: """ - Cancelling a write's caller, either while the source call is still running or while the + Canceling a write's caller, either while the source call is still running or while the write waits to update the cache, does not leave the old value cached once the source call has landed. """ source = _PausingWriteStore() cached = CacheStore(source, cache_store=MemoryStore()) await cached.set("d/k", CPUBuffer.from_bytes(b"old value")) - match cancelled_while: + match canceled_while: case "source_call_running": - # The source call keeps running after its caller is cancelled, as a thread does, + # The source call keeps running after its caller is canceled, as a thread does, # and lands later. A read in between caches what the source holds until then. source.pause = "before" task = asyncio.ensure_future(write(cached)) @@ -1657,6 +1659,7 @@ async def test_cancelled_write_still_updates_the_cache( async with cached._state.lock: pass + await _assert_cache_coherent(cached) await _assert_reads_match_source(cached, "d/k") await _assert_cache_coherent(cached) @@ -1682,8 +1685,8 @@ async def test_read_settling_ahead_of_a_queued_write_is_replaced_by_it() -> None await _assert_cache_coherent(cached) -async def test_cancelled_read_leaves_the_cache_coherent() -> None: - """A read cancelled while waiting to cache its value leaves no trace and no half update.""" +async def test_canceled_read_leaves_the_cache_coherent() -> None: + """A read canceled while waiting to cache its value leaves no trace and no half update.""" source = MemoryStore() await source.set("k", CPUBuffer.from_bytes(b"value")) cached = CacheStore(source, cache_store=MemoryStore()) @@ -1755,10 +1758,10 @@ async def test_cache_store_failure_does_not_leave_the_replaced_value( await _assert_reads_match_source(cached, "other") -class _PartlyFailingDeleteStore(MemoryStore): +class _PartlyFailingDeleteStore(_PausingReadStore): """ - A `MemoryStore` whose deletes, one key at a time, fail after the first one, and whose - `exists` fails while `exists_fails` is true. + A `_PausingReadStore` whose deletes, one key at a time, fail after the first one, and + whose `exists` fails while `exists_fails` is true. """ def __init__(self, *, exists_fails: bool) -> None: @@ -1782,37 +1785,138 @@ async def clear(self) -> None: await self.delete(key) -@pytest.mark.parametrize( +_failing_deletions = pytest.mark.parametrize( "deletion", [lambda cached: cached.delete_dir("d"), lambda cached: cached.clear()], ids=["delete_dir", "clear"], ) + + +@_failing_deletions @pytest.mark.parametrize("exists_fails", [False, True]) +@pytest.mark.parametrize("byte_ranges", [[None, RangeByteRequest(0, 3)], [RangeByteRequest(0, 3)]]) async def test_partly_failed_deletion_drops_deleted_keys( - deletion: Callable[[CacheStore], Awaitable[None]], exists_fails: bool + deletion: Callable[[CacheStore], Awaitable[None]], + exists_fails: bool, + byte_ranges: list[ByteRequest | None], ) -> None: """ - A source deletion that raises after deleting some keys leaves none of those keys cached. - It keeps the entries for keys the source confirms it still holds, and drops them when - the source cannot say. + A source deletion that raises after deleting some keys leaves none of those keys cached, + whether as full values or only as byte ranges. It keeps the entries for keys the source + confirms it still holds, and drops them when the source cannot say. """ source = _PartlyFailingDeleteStore(exists_fails=exists_fails) + source.resume.set() cache = MemoryStore() - cached = CacheStore(source, cache_store=cache) + cached = CacheStore(source, cache_store=cache, cache_set_data=False) for key in ["d/x", "d/y"]: - await cached.set(key, CPUBuffer.from_bytes(key.encode() * 2)) - await cached.get(key, default_buffer_prototype(), RangeByteRequest(0, 3)) + await source.set(key, CPUBuffer.from_bytes(key.encode() * 2)) + for byte_range in byte_ranges: + await cached.get(key, default_buffer_prototype(), byte_range) with pytest.raises(OSError, match="source deletion failed"): await deletion(cached) source.exists_fails = False assert set(source._store_dict) == {"d/y"} - assert set(cache._store_dict) == (set() if exists_fails else {"d/y"}) + kept = set() if exists_fails else {"d/y"} + assert set(cache._store_dict) == (kept if None in byte_ranges else set()) + assert set(cached._state.range_cache) == kept await _assert_cache_coherent(cached) for key in ["d/x", "d/y"]: await _assert_reads_match_source(cached, key) +@_failing_deletions +@pytest.mark.parametrize("byte_range", [None, RangeByteRequest(0, 3)]) +async def test_partly_failed_deletion_supersedes_reads_in_flight( + deletion: Callable[[CacheStore], Awaitable[None]], byte_range: ByteRequest | None +) -> None: + """ + A read that fetched a key before a source deletion removed it and then raised does not + cache the deleted value. + """ + source = _PartlyFailingDeleteStore(exists_fails=False) + for key in ["d/x", "d/y"]: + await source.set(key, CPUBuffer.from_bytes(key.encode() * 2)) + cached = CacheStore(source, cache_store=MemoryStore()) + read = asyncio.create_task(cached.get("d/x", default_buffer_prototype(), byte_range)) + await source.fetched.wait() + with pytest.raises(OSError, match="source deletion failed"): + await deletion(cached) + source.resume.set() + await read + + assert "d/x" not in source._store_dict + await _assert_cache_coherent(cached) + + +@pytest.mark.parametrize("byte_range", [None, RangeByteRequest(0, 3)]) +async def test_clear_cache_keeps_reads_in_flight_supersedable( + byte_range: ByteRequest | None, +) -> None: + """ + `clear_cache` does not forget a read in flight, so a write that lands after it still keeps + the read from caching the value it replaced. + """ + source = _PausingReadStore() + await source.set("k", CPUBuffer.from_bytes(b"old value")) + cached = CacheStore(source, cache_store=MemoryStore(), cache_set_data=False) + read = asyncio.create_task(cached.get("k", default_buffer_prototype(), byte_range)) + await source.fetched.wait() + await cached.clear_cache() + await cached.set("k", CPUBuffer.from_bytes(b"new value")) + source.resume.set() + await read + + await _assert_cache_coherent(cached) + await _assert_reads_match_source(cached, "k") + + +class _FailingReadStore(MemoryStore): + """A `MemoryStore` whose reads raise.""" + + async def get( + self, + key: str, + prototype: BufferPrototype | None = None, + byte_range: ByteRequest | None = None, + ) -> Buffer | None: + raise OSError("source read failed") + + +@pytest.mark.parametrize("byte_range", [None, RangeByteRequest(0, 3)]) +async def test_failed_source_read_leaves_the_cache_unchanged( + byte_range: ByteRequest | None, +) -> None: + """A source read that raises caches nothing and leaves no operation registered.""" + cached = CacheStore(_FailingReadStore(), cache_store=MemoryStore()) + with pytest.raises(OSError, match="source read failed"): + await cached.get("k", default_buffer_prototype(), byte_range) + + await _assert_cache_coherent(cached) + assert cached.cache_stats()["misses"] == 1 + + +async def test_entries_fill_max_size_exactly() -> None: + """ + Entries fill the budget up to exactly `max_size`, and a replacement evicts only what it + must, counting the entry it replaces as free. + """ + source = MemoryStore() + cache = MemoryStore() + cached = CacheStore(source, cache_store=cache, max_size=8) + await cached.set("a", CPUBuffer.from_bytes(b"aaa")) + await cached.set("b", CPUBuffer.from_bytes(b"bbbbb")) + assert set(cache._store_dict) == {"a", "b"} + await cached.set("b", CPUBuffer.from_bytes(b"BBBBB")) + assert set(cache._store_dict) == {"a", "b"} + assert cached.cache_stats()["evictions"] == 0 + await cached.set("c", CPUBuffer.from_bytes(b"cccccccc")) + assert set(cache._store_dict) == {"c"} + assert cached.cache_stats()["evictions"] == 2 + await _assert_cache_coherent(cached) + + async def test_untracked_cache_store_data_is_not_served() -> None: """ Data a cache store already holds without this `CacheStore` tracking it, such as a @@ -1865,7 +1969,8 @@ class _YieldingStore(MemoryStore): A `MemoryStore` that yields to the event loop around every operation, as I/O-backed stores do. How many times it yields is drawn from `schedule`, so concurrent operations interleave in - varied orders. + varied orders. With `fail_deletes`, deletes fail at random, so `delete_dir` and `clear` + can fail partway. """ def __init__( @@ -1874,12 +1979,19 @@ def __init__( *, read_only: bool = False, schedule: random.Random, + fail_deletes: bool = False, ) -> None: super().__init__(store_dict, read_only=read_only) self.schedule = schedule + self.fail_deletes = fail_deletes def with_read_only(self, read_only: bool = False) -> "_YieldingStore": - return type(self)(self._store_dict, read_only=read_only, schedule=self.schedule) + return type(self)( + self._store_dict, + read_only=read_only, + schedule=self.schedule, + fail_deletes=self.fail_deletes, + ) async def _yield(self) -> None: for _ in range(self.schedule.randint(0, 3)): @@ -1908,13 +2020,19 @@ async def set_if_not_exists(self, key: str, value: Buffer) -> None: async def delete(self, key: str) -> None: await self._yield() + if self.fail_deletes and self.schedule.random() < 0.15: + raise OSError("injected source delete failure") await super().delete(key) await self._yield() async def clear(self) -> None: + # Key by key, like a real store's clear: it can fail partway, and it checks read-only. + for key in sorted(self._store_dict): + await self.delete(key) + + async def exists(self, key: str) -> bool: await self._yield() - await super().clear() - await self._yield() + return await super().exists(key) _SM_KEYS = ("a", "b", "d/x", "d/y", "e/z") @@ -1926,21 +2044,23 @@ async def clear(self) -> None: SuffixByteRequest(4), ) _SM_WRITES = frozenset({"set", "delete", "set_if_not_exists", "set_many", "delete_dir", "clear"}) +_SM_DELETIONS = frozenset({"delete", "delete_dir", "clear"}) _sm_keys = st.sampled_from(_SM_KEYS) _sm_values = st.binary(max_size=24) _sm_get = st.tuples(st.just("get"), _sm_keys, st.sampled_from(_SM_BYTE_RANGES)) _sm_set = st.tuples(st.just("set"), _sm_keys, _sm_values) -# Each operation is `(through_read_only_view, (name, *arguments))`. Reads and writes are -# repeated so they outnumber the operations that empty the cache, and the cache fills up. +_sm_delete = st.tuples(st.just("delete"), _sm_keys) +_sm_set_if_not_exists = st.tuples(st.just("set_if_not_exists"), _sm_keys, _sm_values) +_sm_set_many = st.tuples(st.just("set_many"), st.lists(st.tuples(_sm_keys, _sm_values), max_size=3)) +_sm_delete_dir = st.tuples(st.just("delete_dir"), st.sampled_from(["", "d", "d/", "e", "a"])) +# Each operation is `(through_read_only_view, (name, *arguments))`. Operations are repeated to +# weight them: reads and writes outnumber the ones that empty the cache, so it fills up. _sm_operations = st.tuples( st.booleans(), st.one_of( - *([_sm_get] * 5), - *([_sm_set] * 3), - st.tuples(st.just("delete"), _sm_keys), - st.tuples(st.just("set_if_not_exists"), _sm_keys, _sm_values), - st.tuples(st.just("set_many"), st.lists(st.tuples(_sm_keys, _sm_values), max_size=3)), - st.tuples(st.just("delete_dir"), st.sampled_from(["", "d", "d/", "e", "a"])), + *([_sm_get] * 6), + *([_sm_set] * 4), + *([_sm_delete, _sm_set_if_not_exists, _sm_set_many, _sm_delete_dir] * 2), st.tuples(st.just("clear")), st.tuples(st.just("clear_cache")), ), @@ -1972,14 +2092,23 @@ async def _apply_operation(store: CacheStore, operation: tuple[Any, ...]) -> Buf async def _apply_operations( machine: "CacheStoreMachine", operations: list[tuple[bool, tuple[Any, ...]]] ) -> list[Buffer | BaseException | None]: - """Run `operations` concurrently, through the read-only view where drawn.""" - return await asyncio.gather( + """ + Run `operations` concurrently, through the read-only view where drawn. + + No task they start may outlive them: it would keep drawing from the finished example's + `schedule`, and run into the next step. + """ + before = asyncio.all_tasks() + results = await asyncio.gather( *( _apply_operation(machine.read_only if read_only else machine.cached, operation) for read_only, operation in operations ), return_exceptions=True, ) + leftover = asyncio.all_tasks() - before + assert not leftover, f"operations left tasks running: {leftover}" + return results class CacheStoreMachine(RuleBasedStateMachine): @@ -1996,7 +2125,7 @@ class CacheStoreMachine(RuleBasedStateMachine): schedule=st.randoms(use_true_random=False), ) def create(self, max_size: int | None, cache_set_data: bool, schedule: random.Random) -> None: - self.source = _YieldingStore(schedule=schedule) + self.source = _YieldingStore(schedule=schedule, fail_deletes=True) self.cache = _YieldingStore(schedule=schedule) self.cached = CacheStore( self.source, cache_store=self.cache, max_size=max_size, cache_set_data=cache_set_data @@ -2008,14 +2137,19 @@ def _check_results( operations: list[tuple[bool, tuple[Any, ...]]], results: list[Buffer | BaseException | None], ) -> None: - """Only writes through the read-only view may fail, and only because it is read-only.""" - for (read_only, operation), result in zip(operations, results, strict=True): + """ + Only writes through the read-only view may fail, because it is read-only, and + deletions, because of an injected source failure. + """ + for (read_only, (name, *_)), result in zip(operations, results, strict=True): if isinstance(result, BaseException) and not isinstance(result, Exception): # Hypothesis stops an overrunning example from inside the store's `schedule`. raise result - if isinstance(result, BaseException): - if read_only and operation[0] in _SM_WRITES and isinstance(result, ValueError): - continue + if isinstance(result, ValueError) and read_only and name in _SM_WRITES: + assert "read-only" in str(result) + elif isinstance(result, OSError) and name in _SM_DELETIONS: + assert "injected source delete failure" in str(result) + elif isinstance(result, BaseException): raise result @rule(operation=_sm_operations) From 60562290c85f56cf0286cbc7cd2ca125f9912afc Mon Sep 17 00:00:00 2001 From: Rafael Atala Pulzi <105671171+RafaelPulzi@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:53:25 -0300 Subject: [PATCH 08/12] docs: record the 0-d array return of scalar indexing in the 3.0 migration guide (#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. --- changes/3741.doc.md | 1 + docs/user-guide/v3_migration.md | 15 +++++++++++++++ 2 files changed, 16 insertions(+) create mode 100644 changes/3741.doc.md diff --git a/changes/3741.doc.md b/changes/3741.doc.md new file mode 100644 index 0000000000..ccab6b2397 --- /dev/null +++ b/changes/3741.doc.md @@ -0,0 +1 @@ +The 3.0 migration guide now records that indexing a single element of an array returns a 0-dimensional `numpy.ndarray`, where Zarr-Python 2 returned a NumPy scalar, and that arrays whose shape is `()` changed in the other direction. `Array.__getitem__` follows the Python array API standard, so the guide shows `item()` and `[()]` as the ways to get a scalar back. diff --git a/docs/user-guide/v3_migration.md b/docs/user-guide/v3_migration.md index f8c8a99f67..68a042f4c5 100644 --- a/docs/user-guide/v3_migration.md +++ b/docs/user-guide/v3_migration.md @@ -116,6 +116,21 @@ The following sections provide details on breaking changes in Zarr-Python 3. `zarr.core.common.ShapeLike` input rather than separate arguments for each dimension. Use `resize((10,10))` in place of `resize(10,10)`. +4. Indexing a single element returns a 0-dimensional array - a selection that picks out one + element returned a NumPy scalar in Zarr-Python 2. In Zarr-Python 3 it returns a + 0-dimensional `numpy.ndarray`, which follows the + [Python array API standard](https://data-apis.org/array-api/latest/API_specification/generated/array_api.array.__getitem__.html), + where `__getitem__` returns an array. Arrays whose shape is `()` changed in the other + direction: reading one returned a 0-dimensional `numpy.ndarray` in Zarr-Python 2 and + returns a NumPy scalar in Zarr-Python 3. Call `item()` on the result for a Python scalar, + or index it with `()` for a NumPy scalar: + + ```diff + - value = arr[0] # numpy.float64 + + value = arr[0].item() # float + + value = arr[0][()] # numpy.float64 + ``` + ### The Group class 1. Disallow direct construction - use [`zarr.open_group`][] or [`zarr.create_group`][] From 12b472194dd92aa5896722a98b789ec9d198461b Mon Sep 17 00:00:00 2001 From: Harshit-2118 <70027602+Harshit-2118@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:25:32 +0530 Subject: [PATCH 09/12] fix: invalidate CacheStore entries after bulk deletion (#4696) * fix: invalidate CacheStore entries after bulk deletion * chore: use the pull request number for the changelog --- changes/4696.bugfix.md | 1 + src/zarr/experimental/cache_store.py | 20 +++ tests/test_experimental/test_cache_store.py | 145 +++++++++++++++++++- 3 files changed, 165 insertions(+), 1 deletion(-) create mode 100644 changes/4696.bugfix.md diff --git a/changes/4696.bugfix.md b/changes/4696.bugfix.md new file mode 100644 index 0000000000..8e4adce79e --- /dev/null +++ b/changes/4696.bugfix.md @@ -0,0 +1 @@ +Invalidate full-key and byte-range caches when clearing a `CacheStore` or deleting a directory, so subsequent reads do not return deleted data. diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index 20cb4d4c0f..97816c2016 100644 --- a/src/zarr/experimental/cache_store.py +++ b/src/zarr/experimental/cache_store.py @@ -408,6 +408,26 @@ async def delete(self, key: str) -> None: async with self._state.lock: self._remove_from_tracking(key) + async def clear(self) -> None: + """Clear the source store and both caches.""" + await super().clear() + await self.clear_cache() + + async def delete_dir(self, prefix: str) -> None: + """Delete a source directory and invalidate its cached entries.""" + await super().delete_dir(prefix) + await self._cache.delete_dir(prefix) + if prefix != "" and not prefix.endswith("/"): + prefix += "/" + async with self._state.lock: + for key in list(self._state.range_cache): + if key.startswith(prefix): + self._invalidate_range_entries(key) + for entry_key in list(self._state.key_sizes): + if isinstance(entry_key, str) and entry_key.startswith(prefix): + self._state.current_size -= self._state.key_sizes[entry_key] + self._remove_from_tracking(entry_key) + def cache_info(self) -> dict[str, Any]: """Return information about the cache state.""" return { diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py index f688a6ca02..24ef4dc5c8 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -4,14 +4,18 @@ import asyncio import time +from pathlib import Path +from typing import Literal +import numpy as np import pytest +import zarr from zarr.abc.store import RangeByteRequest, Store, SuffixByteRequest from zarr.core.buffer.core import default_buffer_prototype from zarr.core.buffer.cpu import Buffer as CPUBuffer from zarr.experimental.cache_store import CacheStore -from zarr.storage import MemoryStore +from zarr.storage import LocalStore, MemoryStore class TestCacheStore: @@ -167,6 +171,128 @@ async def test_delete_removes_from_both_stores(self, cached_store: CacheStore) - assert not await cached_store._store.exists("delete_key") assert not await cached_store._cache.exists("delete_key") + @pytest.mark.parametrize("operation", ["clear", "delete_dir", "delete_dir_slash"]) + @pytest.mark.parametrize("byte_range", [None, RangeByteRequest(0, 3)]) + async def test_bulk_delete_invalidates_cache( + self, operation: str, byte_range: RangeByteRequest | None + ) -> None: + source = MemoryStore() + cache = MemoryStore() + cached = CacheStore(source, cache_store=cache, max_size=100) + proto = default_buffer_prototype() + keys = ["data/chunk", "data/nested/chunk", "database/chunk", "data"] + value = CPUBuffer.from_bytes(b"abcdef") + for key in keys: + await source.set(key, value) + assert await cached.get(key, proto, byte_range) is not None + # Persistent cache entries may predate this CacheStore's tracking state. + await cache.set("data/stale", value) + before_stats = cached.cache_stats() + + if operation == "clear": + await cached.clear() + else: + await cached.delete_dir("data/" if operation == "delete_dir_slash" else "data") + + removed = keys if operation == "clear" else keys[:2] + retained = [] if operation == "clear" else keys[2:] + for key in removed: + assert not await source.exists(key) + assert await cached.get(key, proto, byte_range) is None + assert not await cache.exists("data/stale") + for key in retained: + assert await source.exists(key) + result = await cached.get(key, proto, byte_range) + assert result is not None + assert result.to_bytes() == (b"abcdef" if byte_range is None else b"abc") + + expected_entries = {key if byte_range is None else (key, byte_range) for key in retained} + assert set(cached._state.cache_order) == expected_entries + assert set(cached._state.key_sizes) == expected_entries + assert set(cached._state.key_insert_times) == expected_entries + assert set(cached._state.range_cache) == (set(retained) if byte_range else set()) + assert cached.cache_info()["current_size"] == len(retained) * ( + len(value) if byte_range is None else 3 + ) + assert cached.cache_stats()["evictions"] == before_stats["evictions"] + # Retained entries are still hits, rather than silently flushed and reloaded. + assert cached.cache_stats()["hits"] == before_stats["hits"] + len(retained) + + async def test_delete_dir_preserves_shared_cache_and_size_budget(self, tmp_path: Path) -> None: + source = MemoryStore() + cached = CacheStore(source, cache_store=LocalStore(tmp_path), max_size=20) + reader = cached.with_read_only(True) + proto = default_buffer_prototype() + byte_range = RangeByteRequest(0, 3) + for key in ["data/chunk", "database/chunk"]: + await cached.set(key, CPUBuffer.from_bytes(b"abcdef")) + await reader.get(key, proto, byte_range) + assert cached.cache_info()["current_size"] == 18 + + await cached.delete_dir("data") + + assert await reader.get("data/chunk", proto) is None + assert await reader.get("data/chunk", proto, byte_range) is None + assert reader.cache_info()["current_size"] == 9 + before_hits = reader.cache_stats()["hits"] + for request in [None, byte_range]: + result = await reader.get("database/chunk", proto, request) + assert result is not None + assert result.to_bytes() == (b"abcdef" if request is None else b"abc") + assert reader.cache_stats()["hits"] == before_hits + 2 + + # The freed space is usable, and the remaining entries stay in LRU order. + await cached.set("next", CPUBuffer.from_bytes(b"0123456789")) + assert reader.cache_info()["current_size"] == 19 + assert reader.cache_stats()["evictions"] == 0 + await cached.set("last", CPUBuffer.from_bytes(b"XYZ")) + assert reader.cache_stats()["evictions"] == 1 + assert reader.cache_info()["current_size"] == 16 + assert not await cached._cache.exists("database/chunk") + assert ("database/chunk", byte_range) in cached._state.cache_order + + async def test_delete_dir_empty_invalidates_both_caches(self) -> None: + source = MemoryStore() + cached = CacheStore(source, cache_store=MemoryStore()) + proto = default_buffer_prototype() + await cached.set("data/chunk", CPUBuffer.from_bytes(b"abcdef")) + await cached.get("data/chunk", proto, RangeByteRequest(0, 3)) + + await cached.delete_dir("") + + assert await cached.get("data/chunk", proto) is None + assert await cached.get("data/chunk", proto, RangeByteRequest(0, 3)) is None + assert cached.cache_info()["current_size"] == 0 + assert not cached._state.cache_order + assert not cached._state.key_sizes + assert not cached._state.key_insert_times + assert not cached._state.range_cache + + @pytest.mark.parametrize("operation", ["clear", "delete_dir"]) + async def test_bulk_delete_source_error_preserves_cache( + self, monkeypatch: pytest.MonkeyPatch, operation: str + ) -> None: + source = MemoryStore() + cached = CacheStore(source, cache_store=MemoryStore()) + proto = default_buffer_prototype() + await cached.set("data/chunk", CPUBuffer.from_bytes(b"abcdef")) + await cached.get("data/chunk", proto, RangeByteRequest(0, 3)) + before_info = cached.cache_info() + + async def fail(*args: object) -> None: + raise OSError("source deletion failed") + + monkeypatch.setattr(source, operation, fail) + deletion = cached.clear() if operation == "clear" else cached.delete_dir("data") + with pytest.raises(OSError, match="source deletion failed"): + await deletion + + assert cached.cache_info() == before_info + for byte_range in [None, RangeByteRequest(0, 3)]: + result = await cached.get("data/chunk", proto, byte_range) + assert result is not None + assert result.to_bytes() == (b"abcdef" if byte_range is None else b"abc") + async def test_exists_checks_source_store( self, cached_store: CacheStore, source_store: Store ) -> None: @@ -1038,6 +1164,23 @@ async def test_delete_invalidates_cached_byte_ranges(self) -> None: assert result is None +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_deleted_cached_array_cannot_be_reopened(zarr_format: Literal[2, 3]) -> None: + source = MemoryStore() + cached = CacheStore(source, cache_store=MemoryStore()) + group = zarr.group(store=cached, zarr_format=zarr_format) + group.create_array("data", data=np.array([10, 20, 30], dtype="i4")) + array = group["data"] + assert isinstance(array, zarr.Array) + np.testing.assert_array_equal(array[:], [10, 20, 30]) + + del group["data"] + + assert list(group.keys()) == [] + with pytest.raises(KeyError): + group["data"] + + def test_cache_store_opts_out_of_sync_io() -> None: """`CacheStore` must not advertise sync IO capability. From 6d624cf99b4869bc32497d5ed92c3dc45140f6c7 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 15:58:25 +0100 Subject: [PATCH 10/12] fix(experimental): release CacheStore tracking before failed-deletion 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 --- src/zarr/experimental/cache_store.py | 69 ++++++++++++--- tests/test_experimental/test_cache_store.py | 96 ++++++++++++++++++--- 2 files changed, 141 insertions(+), 24 deletions(-) diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index 14a469eb6b..292ae3007a 100644 --- a/src/zarr/experimental/cache_store.py +++ b/src/zarr/experimental/cache_store.py @@ -36,6 +36,8 @@ class _CacheState: key_insert_times: dict[_CacheEntryKey, float] = field(default_factory=dict) range_cache: dict[str, dict[ByteRequest, Buffer]] = field(default_factory=dict) pending: dict[str, set[_PendingOp]] = field(default_factory=dict) + # Operations whose callers were canceled, kept referenced until they finish. + orphans: set[asyncio.Task[None]] = field(default_factory=set) @dataclass(slots=True, eq=False) @@ -72,6 +74,11 @@ class CacheStore(WrapperStore[Store]): replaces, and when two writes to one key overlap, the key's entry is dropped rather than guessing which value the source kept. + Canceling a write (`set`, `delete`, `set_if_not_exists`, `delete_dir`, `clear`) does not + stop it: the source call and the cache update run to completion, and an error they raise + afterwards is logged. Many stores cannot stop a write once started (`LocalStore` writes in + a thread), so this is the only way the cache can follow the source exactly. + Parameters ---------- store : Store @@ -199,8 +206,9 @@ async def _install_entry(self, entry_key: _CacheEntryKey, value: Buffer) -> None """Make `value` the cache entry for `entry_key`: write it and track its size and recency. A value larger than `max_size` is not cached, and any entry it replaces is dropped. - Writing and tracking happen in this one locked step, so the cache never holds data - that the size budget does not count. + Writing and tracking happen in this one locked step, so the cache holds no data that + the size budget does not count, unless a cache-store delete failed. Such data is not + served, since only tracked keys are. Must be called while holding self._state.lock. """ @@ -331,6 +339,28 @@ async def _settle_read( else: await self._install_entry(entry_key, result) + async def _run_to_completion(self, operation: Coroutine[Any, Any, None]) -> None: + """Run `operation` as a task that canceling the caller does not stop. + + If the caller is canceled, the task is kept referenced until it finishes, and an error + it raises then is logged, since no caller is left to receive it. + """ + task = asyncio.ensure_future(operation) + try: + await asyncio.shield(task) + except asyncio.CancelledError: + self._state.orphans.add(task) + task.add_done_callback(self._orphan_done) + raise + + def _orphan_done(self, task: asyncio.Task[None]) -> None: + """Forget an operation whose caller was canceled, logging the error it raised.""" + self._state.orphans.discard(task) + if not task.cancelled() and (error := task.exception()) is not None: + logger.warning( + "A CacheStore operation failed after its caller was canceled", exc_info=error + ) + async def _write( self, key: str, write: Coroutine[Any, Any, None], value: Buffer | None ) -> None: @@ -341,7 +371,7 @@ async def _write( keeps writing after its caller is canceled. A write that raises may still have reached the source, so the key's entry is dropped. """ - await asyncio.shield(self._write_and_settle(key, write, value)) + await self._run_to_completion(self._write_and_settle(key, write, value)) async def _write_and_settle( self, key: str, write: Coroutine[Any, Any, None], value: Buffer | None @@ -407,11 +437,24 @@ async def _settle_failed_delete_dir(self, prefix: str) -> None: present = await asyncio.gather( *map(self._store.exists, candidates), return_exceptions=True ) - for key, exists in zip(candidates, present, strict=True): - if exists is not True: - self._supersede(key) - self._invalidate_range_entries(key) - await self._drop_entry(key) + absent = [ + key for key, exists in zip(candidates, present, strict=True) if exists is not True + ] + # Release every absent key before any cache-store I/O, so a failed delete cannot + # leave the later keys tracked. + for key in absent: + self._supersede(key) + self._invalidate_range_entries(key) + self._remove_from_tracking(key) + failures = [ + result + for result in await asyncio.gather( + *map(self._cache.delete, absent), return_exceptions=True + ) + if result is not None + ] + if failures: + raise failures[0] async def _settle_clear(self) -> None: """Drop every cache entry after a source `clear`.""" @@ -439,7 +482,7 @@ async def _fetch( except BaseException: self._end(op) raise - await asyncio.shield(self._settle_read(op, byte_range, result)) + await self._run_to_completion(self._settle_read(op, byte_range, result)) return result async def _get_try_cache( @@ -553,7 +596,7 @@ async def _set_many(self, values: Iterable[tuple[str, Buffer]]) -> None: Only the last value for a repeated key is written, so the source ends up holding it: concurrent `set` calls on one key could leave either value there. Every write ends - before this returns or raises the first write's error, so no write is left running. + before this returns or raises the first write's error. """ results = await asyncio.gather( *starmap(self.set, dict(values).items()), return_exceptions=True @@ -587,7 +630,7 @@ async def clear(self) -> None: dropped. Like `set`, the source call and the cache update run as one task that canceling the caller does not stop. """ - await asyncio.shield(self._clear_and_settle()) + await self._run_to_completion(self._clear_and_settle()) async def _clear_and_settle(self) -> None: """The body of `clear`.""" @@ -605,7 +648,7 @@ async def delete_dir(self, prefix: str) -> None: are dropped. Like `set`, the source call and the cache update run as one task that canceling the caller does not stop. """ - await asyncio.shield(self._delete_dir_and_settle(prefix)) + await self._run_to_completion(self._delete_dir_and_settle(prefix)) async def _delete_dir_and_settle(self, prefix: str) -> None: """The body of `delete_dir`.""" @@ -644,7 +687,7 @@ def cache_stats(self) -> dict[str, Any]: async def clear_cache(self) -> None: """Clear all cached data and tracking information.""" - await asyncio.shield(self._clear_cache_locked()) + await self._run_to_completion(self._clear_cache_locked()) async def _clear_cache_locked(self) -> None: """The body of `clear_cache`.""" diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py index 7c74e76ef0..6b1f69f688 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -3,6 +3,7 @@ """ import asyncio +import logging import random import time from collections.abc import Awaitable, Callable, Coroutine, MutableMapping @@ -1523,10 +1524,13 @@ async def _assert_reads_match_source(cached: CacheStore, key: str) -> None: assert result.to_bytes() == expected.to_bytes() -async def _assert_cache_coherent(cached: CacheStore) -> None: +async def _assert_cache_coherent(cached: CacheStore, *, allow_untracked_data: bool = False) -> None: """ The cache's tracking describes exactly what it holds, and everything it holds equals the source's current value. Both stores must be `MemoryStore`s. + + With `allow_untracked_data`, the cache store may also hold data the tracking does not + describe, as a failed cache-store delete leaves behind; it is never served. """ state = cached._state cache = cached._cache @@ -1539,7 +1543,9 @@ async def _assert_cache_coherent(cached: CacheStore) -> None: if cached.max_size is not None: assert state.current_size <= cached.max_size tracked_keys = {key for key in state.key_sizes if isinstance(key, str)} - assert set(cache._store_dict) == tracked_keys, "cache store and tracking disagree" + assert tracked_keys <= set(cache._store_dict), "tracked keys missing from the cache store" + if not allow_untracked_data: + assert set(cache._store_dict) == tracked_keys, "cache store holds untracked data" tracked_ranges = {key for key in state.key_sizes if isinstance(key, tuple)} assert all(state.range_cache.values()), "empty per-key range dict left behind" assert { @@ -1634,7 +1640,7 @@ async def test_canceled_write_still_updates_the_cache( match canceled_while: case "source_call_running": # The source call keeps running after its caller is canceled, as a thread does, - # and lands later. A read in between caches what the source holds until then. + # and lands later. A read in between must not leave the old value cached. source.pause = "before" task = asyncio.ensure_future(write(cached)) await source.paused.wait() @@ -1750,24 +1756,22 @@ async def test_cache_store_failure_does_not_leave_the_replaced_value( with pytest.raises(OSError, match=f"cache {failing} failed"): await write(cached) - # A failed cache-store delete may leave data behind, but untracked, so it is not served. - state = cached._state - assert state.current_size == sum(state.key_sizes.values()) - assert {key for key in state.key_sizes if isinstance(key, str)} <= set(cache._store_dict) + await _assert_cache_coherent(cached, allow_untracked_data=True) await _assert_reads_match_source(cached, "k") await _assert_reads_match_source(cached, "other") class _PartlyFailingDeleteStore(_PausingReadStore): """ - A `_PausingReadStore` whose deletes, one key at a time, fail after the first one, and - whose `exists` fails while `exists_fails` is true. + A `_PausingReadStore` whose deletes, one key at a time, fail after the first + `succeeding_deletes`, and whose `exists` fails while `exists_fails` is true. """ - def __init__(self, *, exists_fails: bool) -> None: + def __init__(self, *, exists_fails: bool, succeeding_deletes: int = 1) -> None: super().__init__() self.deletes = 0 self.exists_fails = exists_fails + self.succeeding_deletes = succeeding_deletes async def exists(self, key: str) -> bool: if self.exists_fails: @@ -1776,7 +1780,7 @@ async def exists(self, key: str) -> bool: async def delete(self, key: str) -> None: self.deletes += 1 - if self.deletes > 1: + if self.deletes > self.succeeding_deletes: raise OSError("source deletion failed") await super().delete(key) @@ -1826,6 +1830,76 @@ async def test_partly_failed_deletion_drops_deleted_keys( await _assert_reads_match_source(cached, key) +@_failing_deletions +async def test_cache_store_failure_after_partly_failed_deletion_serves_nothing_deleted( + deletion: Callable[[CacheStore], Awaitable[None]], +) -> None: + """ + When dropping the keys a failed source deletion removed fails in the cache store, none of + those keys is served from the cache afterwards. + """ + source = _PartlyFailingDeleteStore(exists_fails=False, succeeding_deletes=2) + source.resume.set() + cache = _FailingCacheStore() + cached = CacheStore(source, cache_store=cache) + for key in ["d/a", "d/b", "d/c"]: + await cached.set(key, CPUBuffer.from_bytes(key.encode() * 2)) + cache.fail_next = "delete" + with pytest.raises(OSError, match="cache delete failed"): + await deletion(cached) + + assert set(source._store_dict) == {"d/c"} + await _assert_cache_coherent(cached, allow_untracked_data=True) + for key in ["d/a", "d/b", "d/c"]: + await _assert_reads_match_source(cached, key) + + +class _FailingWriteStore(MemoryStore): + """ + A `MemoryStore` whose writes fail once `resume` is set, and keep running when their caller + is canceled, as a thread does. + """ + + def __init__(self) -> None: + super().__init__() + self.started = asyncio.Event() + self.resume = asyncio.Event() + + async def _fail_when_resumed(self) -> None: + self.started.set() + await self.resume.wait() + raise OSError("source write failed") + + async def set(self, key: str, value: Buffer, byte_range: tuple[int, int] | None = None) -> None: + await asyncio.shield(self._fail_when_resumed()) + + +async def test_error_after_the_caller_was_canceled_is_logged( + caplog: pytest.LogCaptureFixture, +) -> None: + """ + A write that fails after its caller was canceled logs the error, since no caller is left + to receive it, and leaves nothing behind. + """ + source = _FailingWriteStore() + cached = CacheStore(source, cache_store=MemoryStore()) + task = asyncio.ensure_future(cached.set("k", CPUBuffer.from_bytes(b"value"))) + await source.started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert cached._state.orphans + + with caplog.at_level(logging.WARNING, logger="zarr.experimental.cache_store"): + source.resume.set() + for _ in range(10): + await asyncio.sleep(0) + + assert "failed after its caller was canceled" in caplog.text + assert not cached._state.orphans + await _assert_cache_coherent(cached) + + @_failing_deletions @pytest.mark.parametrize("byte_range", [None, RangeByteRequest(0, 3)]) async def test_partly_failed_deletion_supersedes_reads_in_flight( From 6558a903cecc07c87dcb4e60fea9f9fc0fc6a043 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 16:03:58 +0100 Subject: [PATCH 11/12] refactor(experimental): filter CacheStore delete failures by type 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 --- src/zarr/experimental/cache_store.py | 2 +- tests/test_experimental/test_cache_store.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index 292ae3007a..8a79aa42d0 100644 --- a/src/zarr/experimental/cache_store.py +++ b/src/zarr/experimental/cache_store.py @@ -451,7 +451,7 @@ async def _settle_failed_delete_dir(self, prefix: str) -> None: for result in await asyncio.gather( *map(self._cache.delete, absent), return_exceptions=True ) - if result is not None + if isinstance(result, BaseException) ] if failures: raise failures[0] diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py index 6b1f69f688..a750d8f706 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -1892,7 +1892,9 @@ async def test_error_after_the_caller_was_canceled_is_logged( with caplog.at_level(logging.WARNING, logger="zarr.experimental.cache_store"): source.resume.set() - for _ in range(10): + for _ in range(100): + if not cached._state.orphans: + break await asyncio.sleep(0) assert "failed after its caller was canceled" in caplog.text From 4c572bba5eaaebfd9bbcec7bce6de22a6a4b2317 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 16:05:12 +0100 Subject: [PATCH 12/12] docs: add changelog fragment for #495 Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- changes/495.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changes/495.bugfix.md diff --git a/changes/495.bugfix.md b/changes/495.bugfix.md new file mode 100644 index 0000000000..68d09fafde --- /dev/null +++ b/changes/495.bugfix.md @@ -0,0 +1 @@ +`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.