From eed21c8e4d9a886efd31cddf52c426c7d26c5bb6 Mon Sep 17 00:00:00 2001 From: Harshit-2118 <70027602+Harshit-2118@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:18:31 +0530 Subject: [PATCH 1/6] fix: invalidate CacheStore entries after bulk deletion --- changes/4695.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/4695.bugfix.md diff --git a/changes/4695.bugfix.md b/changes/4695.bugfix.md new file mode 100644 index 0000000000..8e4adce79e --- /dev/null +++ b/changes/4695.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 303de67989d599025c0122e1e5c62f3cdefea676 Mon Sep 17 00:00:00 2001 From: Harshit-2118 <70027602+Harshit-2118@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:20:12 +0530 Subject: [PATCH 2/6] chore: use the pull request number for the changelog --- changes/{4695.bugfix.md => 4696.bugfix.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changes/{4695.bugfix.md => 4696.bugfix.md} (100%) diff --git a/changes/4695.bugfix.md b/changes/4696.bugfix.md similarity index 100% rename from changes/4695.bugfix.md rename to changes/4696.bugfix.md From cb163ed9c07cc136c63f23fb6a3f9c1df20078d9 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 13:36:26 +0100 Subject: [PATCH 3/6] fix(experimental): keep CacheStore coherent for every inherited write CacheStore inherits WrapperStore's mutating methods, which forward straight to the source store. Each one it does not override writes or deletes around the cache, so later reads serve stale data; #4696 fixed this for clear and delete_dir. Close the rest: - `_set_many` writes each pair through `set`. - `set_if_not_exists` drops the cached entries for its key, since whether the source wrote is not reported. - `set_sync` and `delete_sync` raise `TypeError` instead of bypassing the cache; `_supports_sync_io` already keeps zarr's own code off them. A test classifies every WrapperStore method as safe to inherit or required to be overridden, so a method added to WrapperStore fails until it is handled. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/experimental/cache_store.py | 50 +++++++-- tests/test_experimental/test_cache_store.py | 113 ++++++++++++++++++++ 2 files changed, 156 insertions(+), 7 deletions(-) diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index 97816c2016..47bd31c499 100644 --- a/src/zarr/experimental/cache_store.py +++ b/src/zarr/experimental/cache_store.py @@ -5,6 +5,7 @@ import time from collections import OrderedDict from dataclasses import dataclass, field +from itertools import starmap from typing import TYPE_CHECKING, Any, Literal, Self from zarr.abc.store import ByteRequest, Store @@ -13,6 +14,8 @@ logger = logging.getLogger(__name__) if TYPE_CHECKING: + from collections.abc import Iterable + from zarr.core.buffer.core import Buffer, BufferPrototype # A cache entry identifier. Plain ``str`` for full-key entries that live in @@ -331,12 +334,10 @@ async def _get_no_cache( @property def _supports_sync_io(self) -> bool: - # The caching logic lives only in the async get/set/delete overrides; - # the sync methods inherited from `WrapperStore` delegate straight to - # the source store, so a sync-capable consumer (the fused codec - # pipeline) would write and delete around the cache, leaving stale - # entries that later async reads serve as current data. Opt out of - # sync IO until the sync surface is cache-aware. + # The caching logic lives only in the async methods. `set_sync` and + # `delete_sync` refuse to run rather than write around the cache, and + # `get_sync` reads the source without caching, so opt out of sync IO + # until the sync surface is cache-aware. return False async def get( @@ -401,13 +402,48 @@ async def delete(self, key: str) -> None: The key to delete """ await super().delete(key) - # Invalidate all cached byte-range entries + 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) + async def set_if_not_exists(self, key: str, value: Buffer) -> None: + """ + Store data in the underlying store if `key` is absent there, and invalidate its cache. + + 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) + + async def _set_many(self, values: Iterable[tuple[str, Buffer]]) -> None: + """Store each pair through `set`, so the cache sees every write.""" + await asyncio.gather(*starmap(self.set, values)) + + def set_sync(self, key: str, value: Buffer) -> None: + """ + Refuse synchronous writes. + + The cache is maintained only by the async methods, so a synchronous write would change + the source store behind the cache. See `_supports_sync_io`. + """ + raise TypeError(f"{type(self).__name__} does not support synchronous set.") + + def delete_sync(self, key: str) -> None: + """ + Refuse synchronous deletes. + + The cache is maintained only by the async methods, so a synchronous delete would leave + the deleted value in the cache. See `_supports_sync_io`. + """ + raise TypeError(f"{type(self).__name__} does not support synchronous delete.") + async def clear(self) -> None: """Clear the source store and both caches.""" await super().clear() diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py index 24ef4dc5c8..598198bdc9 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -5,6 +5,7 @@ import asyncio import time from pathlib import Path +from types import FunctionType from typing import Literal import numpy as np @@ -16,6 +17,7 @@ from zarr.core.buffer.cpu import Buffer as CPUBuffer from zarr.experimental.cache_store import CacheStore from zarr.storage import LocalStore, MemoryStore +from zarr.storage._wrapper import WrapperStore class TestCacheStore: @@ -1216,3 +1218,114 @@ async def test_cache_coherent_after_fused_pipeline_write() -> None: # must observe the overwrite, not a cached copy of the first write. arr[:] = np.arange(100, 108, dtype="int32") np.testing.assert_array_equal(arr[:], np.arange(100, 108)) + + +# `WrapperStore` methods that `CacheStore` may inherit unchanged: they read from the source store +# (correct, if uncached) or manage the wrapper's lifecycle, so they cannot leave the cache stale. +# Every other `WrapperStore` method writes or deletes, and `CacheStore` must override it. +_WRAPPER_METHODS_SAFE_TO_INHERIT = { + "__enter__", + "__eq__", + "__exit__", + "__init__", + "__repr__", + "__str__", + "_check_writable", + "_ensure_open", + "_get_many", + "_is_open", + "_open", + "close", + "exists", + "get_partial_values", + "get_ranges", + "get_sync", + "is_empty", + "list", + "list_dir", + "list_prefix", + "open", + "read_only", + "supports_deletes", + "supports_listing", + "supports_writes", +} + + +def test_cache_store_overrides_every_wrapper_store_mutator() -> None: + """ + Every `WrapperStore` method that writes or deletes forwards straight to the source store, + around the cache, unless `CacheStore` overrides it. A method added to `WrapperStore` fails + this test until it is classified as safe to inherit or overridden by `CacheStore`. + """ + wrapper_methods = { + name + for name, attr in vars(WrapperStore).items() + if isinstance(attr, FunctionType | property | classmethod | staticmethod) + } + inherited = wrapper_methods - set(vars(CacheStore)) + assert inherited <= _WRAPPER_METHODS_SAFE_TO_INHERIT, ( + inherited - _WRAPPER_METHODS_SAFE_TO_INHERIT + ) + + +@pytest.mark.parametrize("byte_range", [None, RangeByteRequest(0, 3)]) +async def test_set_many_invalidates_cache(byte_range: RangeByteRequest | None) -> None: + """`_set_many` writes through `set`, so a cached value is replaced, not served stale.""" + source = MemoryStore() + cached = CacheStore(source, cache_store=MemoryStore()) + proto = default_buffer_prototype() + await cached.set("k", CPUBuffer.from_bytes(b"old-value")) + assert await cached.get("k", proto, byte_range) is not None + + await cached._set_many([("k", CPUBuffer.from_bytes(b"new-value"))]) + + result = await cached.get("k", proto, byte_range) + assert result is not None + assert result.to_bytes() == (b"new-value" if byte_range is None else b"new") + + +@pytest.mark.parametrize("byte_range", [None, RangeByteRequest(0, 3)]) +async def test_set_if_not_exists_invalidates_cache(byte_range: RangeByteRequest | None) -> None: + """ + `set_if_not_exists` drops the cached entries for its key, so a write to an absent source key + is not hidden by an entry the cache already holds, such as one a persistent cache kept from + an earlier session after the source changed. + """ + source = MemoryStore() + cache = MemoryStore() + cached = CacheStore(source, cache_store=cache) + proto = default_buffer_prototype() + await cached.set("k", CPUBuffer.from_bytes(b"old-value")) + assert await cached.get("k", proto, byte_range) is not None + await source.delete("k") # the source changes behind the cache + + await cached.set_if_not_exists("k", CPUBuffer.from_bytes(b"new-value")) + + result = await cached.get("k", proto, byte_range) + assert result is not None + assert result.to_bytes() == (b"new-value" if byte_range is None else b"new") + # An existing source key is left alone, and the cache still serves its value. + await cached.set_if_not_exists("k", CPUBuffer.from_bytes(b"ignored")) + result = await cached.get("k", proto) + assert result is not None + assert result.to_bytes() == b"new-value" + + +def test_set_sync_raises() -> None: + """A synchronous write would change the source behind the cache, so it is refused.""" + source = MemoryStore() + cached = CacheStore(source, cache_store=MemoryStore()) + with pytest.raises(TypeError, match="^CacheStore does not support synchronous set\\.$"): + cached.set_sync("k", CPUBuffer.from_bytes(b"value")) + assert "k" not in source._store_dict + + +def test_delete_sync_raises() -> None: + """A synchronous delete would leave the deleted value in the cache, so it is refused.""" + source = MemoryStore() + source.set_sync("k", CPUBuffer.from_bytes(b"value")) + cached = CacheStore(source, cache_store=MemoryStore()) + with pytest.raises(TypeError, match="^CacheStore does not support synchronous delete\\.$"): + cached.delete_sync("k") + assert "k" in source._store_dict From 39aed39dee00e67a1df2dc216abbf0328d59be2b Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 13:43:00 +0100 Subject: [PATCH 4/6] fix(experimental): release cached sizes in one place in CacheStore `_remove_from_tracking` dropped an entry from the size map without subtracting it from `current_size`, so `delete`, `set` with `cache_set_data=False`, and a missed read leaked budget. The previous commit made `set_if_not_exists` a new caller, and zarr calls it on the parent group's metadata for every array created, so the leak grew until eviction emptied the cache. `_remove_from_tracking` now releases the size, and `_evict_key`, `_invalidate_range_entries`, `delete_dir` and `_track_entry` all go through it. `_track_entry` releases the entry it replaces before making room, so eviction cannot release that size twice. `_set_many` writes only the last value for a repeated key. Tests check `current_size == sum(key_sizes)` after every mutator, with and without `cache_set_data`, and across repeated array creation. The classification test now covers methods inherited from `Store` as well. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/experimental/cache_store.py | 37 +++++---- tests/test_experimental/test_cache_store.py | 84 +++++++++++++++++++-- 2 files changed, 94 insertions(+), 27 deletions(-) diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index 47bd31c499..68de686cc3 100644 --- a/src/zarr/experimental/cache_store.py +++ b/src/zarr/experimental/cache_store.py @@ -178,8 +178,6 @@ async def _evict_key(self, entry_key: _CacheEntryKey) -> None: For ``(str, ByteRequest)`` keys the entry is removed from the in-memory range cache. """ - key_size = self._state.key_sizes.get(entry_key, 0) - if isinstance(entry_key, str): await self._cache.delete(entry_key) else: @@ -190,10 +188,7 @@ async def _evict_key(self, entry_key: _CacheEntryKey) -> None: if not per_key: del self._state.range_cache[base_key] - self._state.cache_order.pop(entry_key, None) - self._state.key_insert_times.pop(entry_key, None) - self._state.key_sizes.pop(entry_key, None) - self._state.current_size = max(0, self._state.current_size - key_size) + self._remove_from_tracking(entry_key) self._state.evictions += 1 async def _track_entry(self, entry_key: _CacheEntryKey, value: Buffer) -> bool: @@ -212,10 +207,9 @@ async def _track_entry(self, entry_key: _CacheEntryKey, value: Buffer) -> bool: return False async with self._state.lock: - # If key already exists, subtract old size first - if entry_key in self._state.key_sizes: - old_size = self._state.key_sizes[entry_key] - self._state.current_size -= old_size + # 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) @@ -235,13 +229,16 @@ async def _update_access_order(self, entry_key: _CacheEntryKey) -> None: 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. + """Remove an entry from all tracking structures and release its size. + + This is the only place a tracked entry leaves the size accounting, so + `current_size` always equals the sum of `key_sizes`. Must be called while holding self._state.lock. """ self._state.cache_order.pop(entry_key, None) self._state.key_insert_times.pop(entry_key, None) - self._state.key_sizes.pop(entry_key, None) + self._state.current_size -= self._state.key_sizes.pop(entry_key, 0) def _invalidate_range_entries(self, key: str) -> None: """Remove all byte-range entries for *key* from the range cache and tracking. @@ -251,11 +248,7 @@ def _invalidate_range_entries(self, key: str) -> None: per_key = self._state.range_cache.pop(key, None) if per_key is not None: for byte_range in per_key: - entry_key: _CacheEntryKey = (key, byte_range) - entry_size = self._state.key_sizes.pop(entry_key, 0) - self._state.cache_order.pop(entry_key, None) - self._state.key_insert_times.pop(entry_key, None) - self._state.current_size = max(0, self._state.current_size - entry_size) + self._remove_from_tracking((key, byte_range)) # ------------------------------------------------------------------ # get helpers @@ -423,8 +416,13 @@ async def set_if_not_exists(self, key: str, value: Buffer) -> None: await self._invalidate_key(key) async def _set_many(self, values: Iterable[tuple[str, Buffer]]) -> None: - """Store each pair through `set`, so the cache sees every write.""" - await asyncio.gather(*starmap(self.set, values)) + """ + 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. + """ + await asyncio.gather(*starmap(self.set, dict(values).items())) def set_sync(self, key: str, value: Buffer) -> None: """ @@ -461,7 +459,6 @@ async def delete_dir(self, prefix: str) -> None: 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]: diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py index 598198bdc9..aa28af2b20 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -4,6 +4,7 @@ import asyncio import time +from collections.abc import Awaitable, Callable from pathlib import Path from types import FunctionType from typing import Literal @@ -1220,9 +1221,10 @@ async def test_cache_coherent_after_fused_pipeline_write() -> None: np.testing.assert_array_equal(arr[:], np.arange(100, 108)) -# `WrapperStore` methods that `CacheStore` may inherit unchanged: they read from the source store -# (correct, if uncached) or manage the wrapper's lifecycle, so they cannot leave the cache stale. -# Every other `WrapperStore` method writes or deletes, and `CacheStore` must override it. +# `WrapperStore` and `Store` methods that `CacheStore` may inherit unchanged: they read from the +# source store (correct, if uncached), read through `get`, or manage the wrapper's lifecycle, so +# they cannot leave the cache stale. Every other method writes or deletes, and `CacheStore` must +# override it. _WRAPPER_METHODS_SAFE_TO_INHERIT = { "__enter__", "__eq__", @@ -1239,15 +1241,20 @@ async def test_cache_coherent_after_fused_pipeline_write() -> None: "exists", "get_partial_values", "get_ranges", + "get_ranges_sync", "get_sync", + "getsize", + "getsize_prefix", "is_empty", "list", "list_dir", "list_prefix", "open", "read_only", + "supports_consolidated_metadata", "supports_deletes", "supports_listing", + "supports_partial_writes", "supports_writes", } @@ -1255,12 +1262,14 @@ async def test_cache_coherent_after_fused_pipeline_write() -> None: def test_cache_store_overrides_every_wrapper_store_mutator() -> None: """ Every `WrapperStore` method that writes or deletes forwards straight to the source store, - around the cache, unless `CacheStore` overrides it. A method added to `WrapperStore` fails - this test until it is classified as safe to inherit or overridden by `CacheStore`. + around the cache, unless `CacheStore` overrides it. A method added to `WrapperStore` or + `Store` fails this test until it is classified as safe to inherit or overridden by + `CacheStore`. """ wrapper_methods = { name - for name, attr in vars(WrapperStore).items() + for klass in (WrapperStore, Store) + for name, attr in vars(klass).items() if isinstance(attr, FunctionType | property | classmethod | staticmethod) } inherited = wrapper_methods - set(vars(CacheStore)) @@ -1305,7 +1314,7 @@ async def test_set_if_not_exists_invalidates_cache(byte_range: RangeByteRequest result = await cached.get("k", proto, byte_range) assert result is not None assert result.to_bytes() == (b"new-value" if byte_range is None else b"new") - # An existing source key is left alone, and the cache still serves its value. + # An existing source key is left alone; the read is a miss that fetches the source's value. await cached.set_if_not_exists("k", CPUBuffer.from_bytes(b"ignored")) result = await cached.get("k", proto) assert result is not None @@ -1329,3 +1338,64 @@ def test_delete_sync_raises() -> None: with pytest.raises(TypeError, match="^CacheStore does not support synchronous delete\\.$"): cached.delete_sync("k") assert "k" in source._store_dict + + +def _assert_size_accounting(cached: CacheStore) -> None: + """The cache's size budget counts exactly the entries it tracks.""" + assert cached.cache_info()["current_size"] == sum(cached._state.key_sizes.values()) + assert set(cached._state.key_sizes) == set(cached._state.cache_order) + + +@pytest.mark.parametrize( + "mutate", + [ + lambda cached: cached.delete("k"), + lambda cached: cached.set("k", CPUBuffer.from_bytes(b"replaced")), + lambda cached: cached.set_if_not_exists("k", CPUBuffer.from_bytes(b"ignored")), + lambda cached: cached._set_many([("k", CPUBuffer.from_bytes(b"replaced"))]), + lambda cached: cached.delete_dir(""), + lambda cached: cached.clear(), + ], + ids=["delete", "set", "set_if_not_exists", "_set_many", "delete_dir", "clear"], +) +@pytest.mark.parametrize("cache_set_data", [True, False]) +async def test_mutators_keep_size_accounting( + mutate: Callable[[CacheStore], Awaitable[None]], cache_set_data: bool +) -> None: + """ + Every mutator releases the size of each entry it drops, so `current_size` never counts + entries that are gone; a leak would shrink the usable budget until the cache holds nothing. + """ + source = MemoryStore() + cached = CacheStore( + source, cache_store=MemoryStore(), max_size=1000, cache_set_data=cache_set_data + ) + proto = default_buffer_prototype() + await cached.set("k", CPUBuffer.from_bytes(b"value-of-k")) + await cached.set("other", CPUBuffer.from_bytes(b"other-value")) + for byte_range in [None, RangeByteRequest(0, 3)]: + await cached.get("k", proto, byte_range) + await cached.get("other", proto, byte_range) + _assert_size_accounting(cached) + + await mutate(cached) + + _assert_size_accounting(cached) + for key in ["k", "other"]: + for byte_range in [None, RangeByteRequest(0, 3)]: + await cached.get(key, proto, byte_range) + _assert_size_accounting(cached) + + +async def test_array_creation_keeps_size_accounting() -> None: + """ + Creating arrays in a cached group writes the group's metadata with `set_if_not_exists` + each time; the cache's size budget must stay equal to what it tracks. + """ + cached = CacheStore(MemoryStore(), cache_store=MemoryStore(), max_size=3000) + group = zarr.create_group(store=cached) + for i in range(20): + group.create_array(f"a{i}", shape=(4,), dtype="i4") + zarr.open_group(store=cached, mode="r") + _assert_size_accounting(cached) + assert len(cached._state.cache_order) > 1 From fd47472385384635c7c56e36c784f5d807072035 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 13:51:05 +0100 Subject: [PATCH 5/6] fix(experimental): check CacheStore LRU membership under the lock `_update_access_order` tested `entry_key in cache_order` before awaiting the lock, so a concurrent miss that evicted the entry while the hit waited made `move_to_end` raise `KeyError` out of a plain read. Test membership inside the lock. Also test that replacing a tracked value under size pressure keeps the new value cached with its size counted once; no test covered that change from the previous commit. Assisted-by: ClaudeCode:claude-opus-5-5 --- src/zarr/experimental/cache_store.py | 10 +++-- tests/test_experimental/test_cache_store.py | 46 +++++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index 68de686cc3..866b89834f 100644 --- a/src/zarr/experimental/cache_store.py +++ b/src/zarr/experimental/cache_store.py @@ -223,9 +223,13 @@ async def _track_entry(self, entry_key: _CacheEntryKey, value: Buffer) -> bool: return True async def _update_access_order(self, entry_key: _CacheEntryKey) -> None: - """Update the access order for LRU tracking.""" - if entry_key in self._state.cache_order: - async with self._state.lock: + """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. + """ + async with self._state.lock: + 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: diff --git a/tests/test_experimental/test_cache_store.py b/tests/test_experimental/test_cache_store.py index aa28af2b20..38c25157df 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -1399,3 +1399,49 @@ async def test_array_creation_keeps_size_accounting() -> None: zarr.open_group(store=cached, mode="r") _assert_size_accounting(cached) assert len(cached._state.cache_order) > 1 + + +async def test_replacing_an_entry_under_size_pressure_keeps_it_cached() -> None: + """ + Replacing a tracked value releases the old entry before making room, so eviction neither + releases its size twice nor deletes the new value from the cache store. + """ + cache = MemoryStore() + cached = CacheStore(MemoryStore(), cache_store=cache, max_size=10) + await cached.set("a", CPUBuffer.from_bytes(b"aaaaa")) + await cached.set("b", CPUBuffer.from_bytes(b"bbbbb")) + + await cached.set("a", CPUBuffer.from_bytes(b"AAAAAAAA")) + + _assert_size_accounting(cached) + assert list(cached._state.cache_order) == ["a"] + stored = await cache.get("a", default_buffer_prototype()) + assert stored is not None + assert stored.to_bytes() == b"AAAAAAAA" + + +class _SuspendingDeleteStore(MemoryStore): + """A cache store whose `delete` yields to the event loop, as any I/O-backed store does.""" + + async def delete(self, key: str) -> None: + await asyncio.sleep(0) + await super().delete(key) + + +async def test_concurrent_reads_tolerate_eviction() -> None: + """ + A cache hit whose entry is evicted by a concurrent miss, while the hit waits for the lock, + still returns the value instead of raising `KeyError` from the LRU bookkeeping. + """ + source = MemoryStore() + for key in ["a", "b", "c"]: + await source.set(key, CPUBuffer.from_bytes(b"xxxx")) + cached = CacheStore(source, cache_store=_SuspendingDeleteStore(), max_size=8) + proto = default_buffer_prototype() + await cached.get("a", proto) + await cached.get("b", proto) + + results = await asyncio.gather(cached.get("c", proto), cached.get("a", proto)) + + assert [result.to_bytes() for result in results if result is not None] == [b"xxxx", b"xxxx"] + _assert_size_accounting(cached) From 2f24bc9d6755ce8951aa2836c4add8e797a7f63a Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Fri, 4 Dec 2026 13:52:19 +0100 Subject: [PATCH 6/6] docs: add changelog fragment for #494 Assisted-by: ClaudeCode:claude-opus-5-5 --- changes/494.bugfix.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changes/494.bugfix.md diff --git a/changes/494.bugfix.md b/changes/494.bugfix.md new file mode 100644 index 0000000000..dadc2caa54 --- /dev/null +++ b/changes/494.bugfix.md @@ -0,0 +1 @@ +`CacheStore` keeps its cache consistent with the source store for every write and delete it inherits: `set_if_not_exists` and `_set_many` now update the cache, and `set_sync` and `delete_sync` raise `TypeError` instead of writing around it. Its size budget no longer leaks when entries are deleted, and concurrent reads no longer raise `KeyError` when an entry is evicted.