Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/494.bugfix.md
Original file line number Diff line number Diff line change
@@ -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.
93 changes: 65 additions & 28 deletions src/zarr/experimental/cache_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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)
Expand All @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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()
Expand All @@ -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]:
Expand Down
Loading
Loading