Skip to content
Merged
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/4696.bugfix.md
Original file line number Diff line number Diff line change
@@ -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.
20 changes: 20 additions & 0 deletions src/zarr/experimental/cache_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
145 changes: 144 additions & 1 deletion tests/test_experimental/test_cache_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down
Loading