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. diff --git a/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index 97816c2016..866b89834f 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 @@ -175,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: @@ -187,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: @@ -209,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) @@ -226,19 +223,26 @@ 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: - """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. @@ -248,11 +252,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 @@ -331,12 +331,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 +399,53 @@ 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. + + 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: + """ + 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() @@ -425,7 +463,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 24ef4dc5c8..38c25157df 100644 --- a/tests/test_experimental/test_cache_store.py +++ b/tests/test_experimental/test_cache_store.py @@ -4,7 +4,9 @@ import asyncio import time +from collections.abc import Awaitable, Callable from pathlib import Path +from types import FunctionType from typing import Literal import numpy as np @@ -16,6 +18,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 +1219,229 @@ 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` 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__", + "__exit__", + "__init__", + "__repr__", + "__str__", + "_check_writable", + "_ensure_open", + "_get_many", + "_is_open", + "_open", + "close", + "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", +} + + +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` or + `Store` fails this test until it is classified as safe to inherit or overridden by + `CacheStore`. + """ + wrapper_methods = { + name + 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)) + 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; 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 + 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 + + +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 + + +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)