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/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/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. 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`][] 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/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/src/zarr/experimental/cache_store.py b/src/zarr/experimental/cache_store.py index 866b89834f..8a79aa42d0 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,25 @@ 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) + # Operations whose callers were canceled, kept referenced until they finish. + orphans: set[asyncio.Task[None]] = field(default_factory=set) + + +@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 +69,16 @@ 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. + + 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 @@ -156,28 +185,66 @@ 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 + + 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 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. + """ + 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) + try: + await self._accommodate_value(value_size) + if isinstance(entry_key, str): + await self._cache.set(entry_key, 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 + 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. + Tracking is released first, so the entry is no longer served even if the cache-store + delete fails. - 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. + 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: @@ -188,49 +255,15 @@ async def _evict_key(self, entry_key: _CacheEntryKey) -> 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. - 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. @@ -254,51 +287,217 @@ 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. + """ + 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() + # ------------------------------------------------------------------ - # 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 _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: + """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 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 canceled. A write that raises may still have + reached the source, so the key's entry is dropped. + """ + 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 + ) -> None: + """The body of `_write`.""" + op = self._begin(key) + try: + await write + except BaseException: + await self._settle_write(op, None) + raise + 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`. + + `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) + 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_failed_delete_dir(self, prefix: str) -> None: + """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. 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 += "/" + 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), return_exceptions=True + ) + 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 isinstance(result, BaseException) + ] + if failures: + raise failures[0] + + 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 canceled 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 self._run_to_completion(self._settle_read(op, byte_range, result)) + return result async def _get_try_cache( self, key: str, prototype: BufferPrototype, byte_range: ByteRequest | None = None ) -> 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) @@ -313,21 +512,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 +568,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 +579,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,17 +588,22 @@ 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. Every write ends + before this returns or raises the first write's error. """ - 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: """ @@ -447,23 +624,40 @@ 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.""" - await super().clear() - await self.clear_cache() + """Clear the source store and both caches. + + 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 + canceling the caller does not stop. + """ + await self._run_to_completion(self._clear_and_settle()) + + async def _clear_and_settle(self) -> None: + """The body of `clear`.""" + try: + await super().clear() + except BaseException: + await self._settle_failed_delete_dir("") + raise + await self._settle_clear() 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._remove_from_tracking(entry_key) + """Delete a source directory and invalidate its cached entries. + + 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 + canceling the caller does not stop. + """ + 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`.""" + try: + await super().delete_dir(prefix) + except BaseException: + await self._settle_failed_delete_dir(prefix) + raise + await self._settle_delete_dir(prefix) def cache_info(self) -> dict[str, Any]: """Return information about the cache state.""" @@ -493,17 +687,12 @@ 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() + await self._run_to_completion(self._clear_cache_locked()) - # Reset tracking + async def _clear_cache_locked(self) -> None: + """The body of `clear_cache`.""" 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_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", " 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,802 @@ 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 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 canceled. + """ + + def __init__(self) -> None: + super().__init__() + self.pause: Literal["never", "before", "after"] = "never" + self.paused = asyncio.Event() + self.resume = asyncio.Event() + + 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 asyncio.shield(self._paused(super().set(key, value, byte_range))) + + async def delete(self, key: str) -> None: + await asyncio.shield(self._paused(super().delete(key))) + + async def clear(self) -> None: + await asyncio.shield(self._paused(super().clear())) + + +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() + + +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 + 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 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 { + (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", + [ + 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_cache_coherent(cached) + await _assert_reads_match_source(cached, "d/k") + await _assert_cache_coherent(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() + cache = MemoryStore() + cached = CacheStore(source, cache_store=cache) + source.pause = "after" + first = asyncio.create_task(cached.set("d/k", CPUBuffer.from_bytes(b"first value"))) + await source.paused.wait() + source.pause = "never" + + 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_cache_coherent(cached) + await _assert_reads_match_source(cached, "d/k") + await _assert_cache_coherent(cached) + + +@_cache_writes +@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: + """ + 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 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 must not leave the old value cached. + source.pause = "before" + task = asyncio.ensure_future(write(cached)) + 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: + 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_cache_coherent(cached) + await _assert_reads_match_source(cached, "d/k") + 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_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()) + 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( + ("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 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() + 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 write(cached) + + 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 + `succeeding_deletes`, and whose `exists` fails while `exists_fails` is true. + """ + + 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: + raise OSError("source unreachable") + return await super().exists(key) + + async def delete(self, key: str) -> None: + self.deletes += 1 + if self.deletes > self.succeeding_deletes: + 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) + + +_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, + byte_ranges: list[ByteRequest | None], +) -> None: + """ + 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, cache_set_data=False) + for key in ["d/x", "d/y"]: + 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"} + 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 +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(100): + if not cached._state.orphans: + break + 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( + 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 + 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: + """ + 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() + 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 == {} + await _assert_cache_coherent(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. With `fail_deletes`, deletes fail at random, so `delete_dir` and `clear` + can fail partway. + """ + + def __init__( + self, + store_dict: MutableMapping[str, Buffer] | None = None, + *, + 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, + fail_deletes=self.fail_deletes, + ) + + 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() + 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() + return await super().exists(key) + + +_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_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) +_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] * 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")), + ), +) + + +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. + + 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): + """ + 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), st.integers(4, 12)), + 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, 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 + ) + 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, 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, 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) + 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]) + 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: + """Run operations concurrently, so their awaits interleave.""" + self._check_results(operations, sync(_apply_operations(self, operations))) + + @invariant() + def cache_is_coherent(self) -> None: + sync(_assert_cache_coherent(self.cached)) + + +TestCacheStoreMachine = CacheStoreMachine.TestCase diff --git a/tests/test_fastpath_equivalence.py b/tests/test_fastpath_equivalence.py index 9a2f782d13..b5014fd071 100644 --- a/tests/test_fastpath_equivalence.py +++ b/tests/test_fastpath_equivalence.py @@ -37,9 +37,17 @@ from zarr.storage import MemoryStore _DTYPES = st.sampled_from(["uint8", "int16", "float32"]) +# The whole-shard bulk decode also takes structured data types. Integer fields +# only: structured arrays compare field-wise with `==`, so NaN would never match. +_BULK_DTYPES = st.one_of( + _DTYPES.map(np.dtype), + st.just(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 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"]