From 67b05506d4cd837f0b157091ef7b47cb969c3708 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Thu, 3 Dec 2026 13:03:16 +0100 Subject: [PATCH 1/2] feat(zarr-storage): add a new store API in zarr_storage.experimental The code of d-v-b/zarr-python#488 (`Store` and `AsyncStore` views over capability backends, contexts, locations, the conformance suite), moved from `zarr_storage` to `zarr_storage.experimental`. Apart from import paths, the syntax trees equal fce03f91e's except that `Buffer` comes from `collections.abc`, since the package requires Python 3.12, and that `__version__` stays in `zarr_storage`. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/zarr-storage.yml | 8 +- packages/zarr-storage/DESIGN.md | 478 +++++++ packages/zarr-storage/README.md | 11 +- packages/zarr-storage/changes/0001.feature.md | 1 + .../zarr-storage/docs/api/experimental.md | 5 + .../docs/api/experimental_backends.md | 5 + .../docs/api/experimental_testing.md | 5 + packages/zarr-storage/docs/api/index.md | 8 + packages/zarr-storage/docs/design.md | 4 + packages/zarr-storage/docs/experimental.md | 60 + packages/zarr-storage/docs/index.md | 7 +- packages/zarr-storage/justfile | 3 +- packages/zarr-storage/mkdocs.yml | 5 + packages/zarr-storage/pyproject.toml | 47 +- .../zarr-storage/src/zarr_storage/__init__.py | 1 + .../src/zarr_storage/experimental/__init__.py | 122 ++ .../src/zarr_storage/experimental/_batch.py | 124 ++ .../src/zarr_storage/experimental/_buffers.py | 41 + .../zarr_storage/experimental/_byte_range.py | 38 + .../src/zarr_storage/experimental/_errors.py | 90 ++ .../src/zarr_storage/experimental/_keys.py | 71 + .../zarr_storage/experimental/_protocols.py | 352 +++++ .../zarr_storage/experimental/_resources.py | 538 ++++++++ .../src/zarr_storage/experimental/_store.py | 1021 ++++++++++++++ .../src/zarr_storage/experimental/_types.py | 221 +++ .../experimental/backends/__init__.py | 24 + .../experimental/backends/_common.py | 99 ++ .../experimental/backends/_local.py | 996 ++++++++++++++ .../experimental/backends/_memory.py | 266 ++++ .../experimental/backends/_obstore.py | 951 +++++++++++++ .../experimental/testing/__init__.py | 38 + .../zarr_storage/experimental/testing/_api.py | 262 ++++ .../experimental/testing/_stateful.py | 357 +++++ .../experimental/testing/_suite.py | 1209 +++++++++++++++++ packages/zarr-storage/tests/__init__.py | 0 .../tests/experimental/__init__.py | 0 .../tests/experimental/test_batch.py | 119 ++ .../tests/experimental/test_local.py | 549 ++++++++ .../tests/experimental/test_memory.py | 43 + .../tests/experimental/test_obstore.py | 319 +++++ .../tests/experimental/test_package.py | 17 + .../tests/experimental/test_resources.py | 577 ++++++++ .../tests/experimental/test_store.py | 422 ++++++ packages/zarr-storage/uv.lock | 8 +- 44 files changed, 9505 insertions(+), 17 deletions(-) create mode 100644 packages/zarr-storage/DESIGN.md create mode 100644 packages/zarr-storage/changes/0001.feature.md create mode 100644 packages/zarr-storage/docs/api/experimental.md create mode 100644 packages/zarr-storage/docs/api/experimental_backends.md create mode 100644 packages/zarr-storage/docs/api/experimental_testing.md create mode 100644 packages/zarr-storage/docs/design.md create mode 100644 packages/zarr-storage/docs/experimental.md create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/__init__.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/_batch.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/_buffers.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/_byte_range.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/_errors.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/_keys.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/_protocols.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/_resources.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/_store.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/_types.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/backends/__init__.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/backends/_common.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/backends/_local.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/backends/_memory.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/backends/_obstore.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/testing/__init__.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/testing/_api.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/testing/_stateful.py create mode 100644 packages/zarr-storage/src/zarr_storage/experimental/testing/_suite.py create mode 100644 packages/zarr-storage/tests/__init__.py create mode 100644 packages/zarr-storage/tests/experimental/__init__.py create mode 100644 packages/zarr-storage/tests/experimental/test_batch.py create mode 100644 packages/zarr-storage/tests/experimental/test_local.py create mode 100644 packages/zarr-storage/tests/experimental/test_memory.py create mode 100644 packages/zarr-storage/tests/experimental/test_obstore.py create mode 100644 packages/zarr-storage/tests/experimental/test_package.py create mode 100644 packages/zarr-storage/tests/experimental/test_resources.py create mode 100644 packages/zarr-storage/tests/experimental/test_store.py diff --git a/.github/workflows/zarr-storage.yml b/.github/workflows/zarr-storage.yml index 12c50884ae..fe65fec42c 100644 --- a/.github/workflows/zarr-storage.yml +++ b/.github/workflows/zarr-storage.yml @@ -87,8 +87,8 @@ jobs: - name: Run ruff run: just lint - mypy: - name: mypy + typecheck: + name: mypy and pyright runs-on: ubuntu-latest defaults: run: @@ -107,7 +107,7 @@ jobs: with: repo: casey/just version: 1.58.0 - - name: Run mypy + - name: Run mypy and pyright run: just typecheck legacy-in-sync: @@ -158,7 +158,7 @@ jobs: zarr-storage-complete: name: zarr-storage complete - needs: [test, ruff, mypy, legacy-in-sync, docs] + needs: [test, ruff, typecheck, legacy-in-sync, docs] if: always() runs-on: ubuntu-latest steps: diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md new file mode 100644 index 0000000000..a0a92c6446 --- /dev/null +++ b/packages/zarr-storage/DESIGN.md @@ -0,0 +1,478 @@ +# zarr-storage design (v0) + +Status: experimental; any release may change it. This is the contract that the code in +`zarr_storage.experimental` and its conformance suite implement. It doesn't apply to +`zarr_storage.legacy`, the store API of zarr-python 3 that this one is meant to succeed. "The legacy +API" below means that one. +It is built in iterations; each iteration ends with every backend passing the shared conformance +suite. + +Sources, and what each contributed: + +- **An earlier prototype of this package**: capability protocols instead of a class hierarchy, a + sync floor with an async family beside it, generations and result types, `store / "sub"`. +- **TensorStore**: a store is a driver plus a path (`KvStore{driver, path}`); generations with + "unconditional" and "absent" meanings; reserved file-name suffixes for the file driver's own files; + in-flight operations outlive the last reference. +- **zarrs**: `list_dir` returning keys and prefixes; the `StoreKey`/`StorePrefix` grammar; a byte-range + type with suffix ranges; a missing key is a value (`Option`), not an error. +- **Earlier zarr-python store proposals**: result types and `ObjectMetadata`, conditional writes + that report a refusal instead of raising, the conformance-suite layout. +- **HTTP and Rust `object_store`**: a missing key and an unchanged value are outcomes (`404`, `304`), + not errors; conditional operations are their own methods (`put` vs `put_opts`). +- **zarr-python's store bugs**: directory prefixes, `Key | Prefix | Entry` listing, `delete` vs `delete_dir`, + views with the root applied once, the constructed store owns the backend, no value equality. +- **The roadmap**: separate sync and async surfaces, reads into caller-provided buffers, typed explicit + configuration, transactions later. + +## Shape + +``` +Backend capability protocols over backend paths; owns shared state and lifecycle + ▲ +_View (backend, root, read_only, context, owner): validates keys, applies the root, + ▲ relativizes listings, enforces read-only, limits and schedules every operation with + its context's resources; `store / "a"` is a view on the same backend +Store the operations as sync methods; `close()`, `with`; `as_async()` +AsyncStore the same names as coroutines; `aclose()`, `async with`; `as_sync()` +``` + +A **backend** is an object that implements some capability protocols (`Readable`, `ReadableInto`, +`Writable`, `Listable`, `WritableIfMatch`, `DeletableIfMatch`, the batch protocols `ReadableMany`, +`ReadableIntoMany` and `WritableMany`, their async twins, and `ClosableAsync`) on *backend paths*: +`/`-separated strings, already joined with the root. Every backend also names its `location`, where +its keys live (see "Views, lifecycle, identity"). Backends never see relative keys and never +join or strip paths. They hold everything that must exist once per backend: the dict, the +filesystem root, a client, locks. They hold no thread pools or limits: a backend names the +`resource_key` its operations are limited under, and the store draws the resources from its +context (see "Contexts"). Backends must be thread-safe. + +A **`Store`** or **`AsyncStore`** is the only object users hold. Each is a view: a backend plus a +root, under a context. All key validation, root joining, listing relativization, read-only +enforcement and resource limiting happen in their shared base, once, so no backend can get them +wrong on its own (the source of most bugs in the legacy API: #2190, #2467, #3639, #3922, #4204, +#4452). + +**Sync and async are two classes** (as zarrs has separate sync and async storage traits): `Store` +calls a backend's sync protocols, and `AsyncStore` its async ones where the backend has them and +its sync ones on the context's thread pool otherwise (zarrs's `SyncToAsyncStorageAdapter`, with +the pool in place of its `spawn_blocking`), under the same method names, so `store.get(k)` and +`await astore.get(k)` read the same way and neither class carries the other's methods. A backend +that only blocks, such as a filesystem, needs no async code. Every backend serves both; `store.as_async()` and `astore.as_sync()` are +views on the same backend that don't own it. Lifecycle differs too: `Store` has `close()` and +`with`, `AsyncStore` has `await aclose()` and `async with`, which awaits a `ClosableAsync` +backend's `aclose` (a backend whose cleanup awaits a client session) and calls `close` on any other. + +## Keys and directories + +- **Key:** a string with no leading `/`, no trailing `/`, no empty segment, no `.` or `..` segment, no + NUL character, and not empty. Validated by `Store` on every key argument; `InvalidKeyError` + otherwise. A backend may refuse more with `InvalidKeyError`: the local backend refuses its own + reserved suffix in any case (as TensorStore's file driver does), names too long for the filesystem, and on + Windows the names Windows reads as something else (`:`, `\`, device names like `NUL`, a trailing `.` + or space). +- **Directory:** every prefix argument names a directory. `""` is the root; `"a"` and `"a/"` are the same + directory; otherwise it follows the key grammar. `list("lat")` never sees `lat_bnds/…`. +- **Root:** a store's root is a directory in the backend. `store / "a/b"` appends to it. + +## Operations (`Store`; `AsyncStore` has each under the same name, as a coroutine or async iterator) + +| Method | Returns | Notes | +|---|---|---| +| `get(key, *, byte_range=None)` | `Found \| Missing` | | +| `get_if_changed(key, generation, *, byte_range=None)` | `Found \| Missing \| Unchanged` | `Unchanged` without reading bytes when the value still has `generation` (HTTP `If-None-Match`), to revalidate a cached copy | +| `get_ranges(key, ranges)` | `FoundRanges \| Missing` | all parts from one generation (object stores pin later reads to the first read's generation, and fall back to one whole read if it changed) | +| `get_into(key, out, *, byte_range=None)` | `Copied \| Missing` | `ReadableInto[O]` capability; `Copied.size` bytes written into `out`, a buffer the caller allocated, of the type the backend reads into (see below); `ValueError` if it is too small or can't be written | +| `head(key)` | `ObjectMetadata \| Missing` | size, generation, last-modified | +| `exists(key)` | `bool` | | +| `put(key, value)` | `Written` | `value` is any C-contiguous buffer, copied; `KeyConflictError` where the backend can't hold a key and a directory with one name | +| `put_if_absent(key, value)` | `Written \| Rejected` | `Rejected` carries the generation of the value already there | +| `put_if_match(key, value, generation)` | `Written \| Rejected \| Missing` | `WritableIfMatch` capability; compare-and-swap | +| `delete(key)` | `Deleted \| Missing` | one key; deleting a directory name finds it `Missing` | +| `delete_if_match(key, generation)` | `Deleted \| Rejected \| Missing` | `DeletableIfMatch` capability | +| `delete_dir(directory)` | `None` | everything under the directory | +| `get_many(requests)` | `Iterator[(request, Found \| Missing)]` | a request is a key or `(key, byte_range)`, echoed back; lazy, in the order reads finish | +| `get_into_many(requests)` | `Iterator[(request, Copied \| Missing)]` | `(key, out)` or `(key, out, byte_range)`; `out` typed as for `get_into` | +| `put_many(items)` | `list[(key, Written)]` | `(key, value)` pairs; eager, results in the order given; a key named twice raises `ValueError` | +| `delete_many(keys)` | `list[(key, Deleted \| Missing)]` | as `put_many` | +| `list(directory="")` | `Iterator[str]` | every key under the directory, relative to the store's root | +| `list_dir(directory="")` | `Iterator[Key \| Prefix \| Entry]` | direct children, names relative to the directory; `Entry` when the backend can't tell; a `Prefix` may hold no keys (an empty directory on a filesystem) | + +**Results are closed unions of small frozen types**, one per outcome, so a `match` handles each and a +type checker sees what's left. A method returns only the outcomes it can produce: `get` can't be +`Unchanged`, `put` can't be `Rejected`. That is why conditional operations are separate methods +rather than keyword arguments, and it lets a capability a backend lacks be a type error +(`delete_if_match` on an object store) instead of a runtime refusal. A refusal some stores can only +discover at runtime (`put_if_match` on obstore's `LocalStore`, or on a filesystem that rounds file +times) still raises `UnsupportedOperationError`. `Missing` and the read results carry `read_at`, when +the backend read, so a cache can age an absence like a value. + +**Reads into caller buffers, on any device.** `ReadableInto` is generic in the buffer type the +backend writes into, and `Store.get_into` accepts exactly that type. The built-in backends are +`ReadableInto[Buffer]`: any writable C-contiguous host buffer. A GPU direct storage backend (cuFile, +kvikio) would be `ReadableInto[DeviceBuffer]`, reading from disk straight into device memory, and +passing it a host buffer is a type error (and the reverse). The caller allocates, because the caller +knows the size and the device; the store never needs an allocator, so it stays free of Zarr's buffer +classes (zarr-python's `prototype` argument puts allocation in the store instead). `get` keeps +returning host bytes, which is what metadata documents need. Not yet: `get_ranges_into` (several +ranges into several buffers, from one generation, for sharded chunks) and the write-side twin +`put_from`. + +**Batches are for throughput, not atomicity.** `get_many`, `get_into_many`, `put_many` and +`delete_many` each do what a loop of the single operation would, and promise nothing more: each +read finds whatever generation is current when it runs, and a batch of writes can land partly +(`get_ranges`, which reads several parts of one value from one generation, is a consistency +guarantee, not a batch). Each result is paired with its request, so `dict(store.get_many(keys))` +works and order doesn't matter. Reads are lazy and come in the order they finish, so a caller can +decode chunks as they arrive. Writes are eager, because a lazy write nobody iterates would silently +write nothing; they return results in the order given. Every key is checked, and every value viewed, +before any operation starts, and a write batch that names a key twice raises, since which write +wins would be a race. If operations raise, the batch starts no new ones (a `Store` batch cancels +those still queued on the pool), lets those running finish, +and raises `BatchError`, an `ExceptionGroup` of the failures whose `completed` holds the writes that +landed with their results and whose `remaining` holds the requests that failed or never started +(`except*` keeps both). Conditional operations have no batch form: compare-and-swap coordinates +single documents, and a batch of it belongs to transactions. + +`Store` provides every batch method for any backend that can read or write, running single +operations concurrently under the view's context: `Store` on the context's thread pool, `AsyncStore` +as tasks, at most the context limiter's `limit` at once, each holding its own slot. A backend with +a batch capability (`ReadableMany`, `ReadableIntoMany[O]`, `WritableMany`, and async twins) is +used instead, for batching the store itself can do (one request for many keys, one GPU +submission); it receives the context so it can draw on the same resources. The rule for any +fallback: `Store` may fall back when only speed differs, never when behavior does. A batch of single +operations returns what a native batch would; a `get_into` that read and then copied would not put +the bytes where the backend's buffer type says, which is why `get_into` has no fallback. One pair of batch runners +implements the windowing and failure rule for every fallback. + +Listing arguments are checked when the method is called; the items are produced lazily, and taking +one after the store closes raises `StoreClosedError`. + +**Byte ranges** (zarrs `ByteRange`, TensorStore `OptionalByteRangeRequest`): `RangeRequest(start, end)`, +`OffsetRequest(start)`, `SuffixRequest(length)`. An end past the value is clamped; a start past the value +raises `InvalidByteRangeError`; a suffix longer than the value returns the whole value. + +**Generations** are opaque and compared only by equality. Backends mint them: a counter (memory), +`(device, inode, mtime_ns, size)` (local, as TensorStore's file driver), an ETag (object stores). +A store that reports neither an ETag nor a version (an HTTP server that sends no ETag) gives every +value the same generation, which identifies nothing: `get_if_changed` never answers `Unchanged` for +it, and `put_if_match` raises `UnsupportedOperationError`. + +## Views, lifecycle, identity + +- `store / "a"`, `store.as_read_only()`, `store.with_context(ctx)`, `store.limited(n)` and + `store.as_async()` (or `as_sync()`) return views on the same backend. A view keeps its context + unless it is given another. No view of a read-only store accepts writes. Names follow one rule: + `as_*` changes the surface or the permission (`as_async`, `as_read_only`), `with_*` gives the + view a value (`with_context`), and `limited(n)` narrows the limit it already has. +- Construct one store per backend. The constructed store sees the backend from its root and owns + it: `close()` (`aclose()` on an `AsyncStore`) on it closes the backend; on a derived view it does + nothing. There is no `root` argument, so a second store over a backend is a view (`store / "a"`), + not a second owner. After the backend closes, every view raises `StoreClosedError`. +- No value equality: `==` is identity. `shares_backend(other)` asks whether two stores use one + backend object (and so share its state and lifecycle); `overlaps(other)` asks whether a key could + be visible through both, even over different backend objects. Each backend names where its keys + live as a `Location`, a `space` and a `path` in it (TensorStore's kvstore is likewise a driver + spec plus a path): `("file",)` and the resolved root for `LocalBackend` and obstore's + `LocalStore` alike (an obstore prefix resolved once, when the backend is made), the endpoint and + bucket (or account and container) and prefix for object stores, the scheme and host with the + URL's path for HTTP, and an identity-only space for a memory store or a store of an unknown kind. + User names, passwords and query strings are dropped from URLs and endpoints. `copy.copy` of a + store is the store itself, so it can't make a second owner. + A store's `location` appends its root, and two stores overlap when their spaces are equal and one + path lies within the other. A location never holds credentials. It can't see aliases the + filesystem makes (hard links, bind mounts, case-insensitive names) or two endpoints that serve + one bucket. +- Pickling carries the backend's configuration and the view's root. A pickled memory store carries a + copy of its data. + +## Errors + +`StorageError` is the base. `InvalidKeyError` and `InvalidByteRangeError` also subclass `ValueError`; +`UnsupportedOperationError` also subclasses `NotImplementedError`. `KeyConflictError`, `ReadOnlyError` +and `StoreClosedError` complete the set. A missing key is not an error, and neither is reading under a +key (`a/b` when `a` is a key): that reads as absent. + +## Backends + +| Backend | Generations | `put_if_match` / `delete_if_match` | Key and directory with one name | Pickles | +|---|---|---|---|---| +| `MemoryBackend` | counter | yes / yes | yes | a copy of the data | +| `LocalBackend` | `(dev, inode, mtime_ns, size)`, with each write stamping a unique ns mtime | yes / yes, on filesystems that keep ns times | no (`KeyConflictError`) | the root | +| `ObjectStoreBackend` | ETag and version (obstore's `LocalStore` ETag can repeat on ext4) | if the store supports it / not implemented | as the store does | as the store does | + +Every backend has `put_if_absent` and `get_if_changed`. `LocalBackend` is sync only; `AsyncStore` +runs its operations on the context's pool. `MemoryBackend` and `ObjectStoreBackend` are also +natively async. Their resource keys are `"local"`, `"memory"`, and `"obstore."` plus the obstore +store's class name, so every S3 backend in a process shares one limit by default. + +`LocalBackend` stages each write in a reserved directory under the root and renames it into place, +holding the lock of the key's directory; the lock lives in that directory, so overlapping roots and +other processes share it. Locks are always taken ancestor before descendant. `delete_dir` removes a +tree bottom-up under each directory's lock, so a write in progress finishes before its directory +goes. Deletes, and writes whose precondition fails, can leave directories behind (pruning raced +every concurrent write). A later write of a key with such a directory's name reclaims it with +`rmdir`, only if no key lies under it, so a reclaim can never remove a key; otherwise the write +raises `KeyConflictError`, whatever its preconditions. A symlink to a file in a key's place is that +key's file. The tree that listings and `delete_dir` walk stops at a symlink to a directory (or a +Windows junction), since what lies beyond one may lie outside the root: listings leave such a link +out and return nothing for a directory reached through one, and `delete_dir` deletes nothing +through one. Where the platform allows (`dir_fd`; not Windows), `delete_dir` walks by file +descriptor, opening each directory relative to its parent and never through a symlink, as +`shutil.rmtree` does, so a directory swapped for a symlink mid-walk is unlinked as a link, never +followed. Single-key operations go through a symlinked directory, as the filesystem resolves the +path. Dangling symlinks and special files (a FIFO, a device) are not keys: they read as absent, +and are never opened in a way that blocks. Each write stamps its file with a nanosecond mtime unique within the process, because +filesystems such as ext4 reuse inodes at once and advance mtimes only per clock tick; on a +filesystem that rounds file times, `put_if_match` and `delete_if_match` raise +`UnsupportedOperationError`. +`LocalBackend` doesn't sync to disk, and needs a root that doesn't span filesystems. +`LocalBackend(root)` changes nothing on disk and needs `root` to be a directory already; +`LocalBackend.create(root)` makes it, and any missing parents, first. + +`ObjectStoreBackend.get_ranges` reads the first range unpinned, takes the generation and size from +that response, and reads the rest pinned to it (`If-Match`, and checked against each response); +on a mismatch it reads the value once, whole, and slices it. It does not use obstore's own +`get_ranges`, which can panic when a value shrinks mid-read. Only obstore's `LocalStore` reads a +refusal under a file as an absent key (judged from the refusal's own `ENOTDIR`, since looking at +the parents afterwards races a concurrent delete of the parent), and only there does a write reclaim an empty directory in +its way; for every other store, an error is raised. obstore's `LocalStore` has no locking, so +writes that concurrently create and remove the same directories can surface its errors. + +## Conformance suite + +`zarr_storage.experimental.testing.StoreSuite` holds the contract every backend meets; optional capabilities come +as mixins a backend's test class adds (`ConditionalPutSuite`, `ConditionalDeleteSuite`, +`ConditionalRaceSuite`, `KeyAndDirectorySuite`, `PickleSuite`, `UniqueGenerationsSuite`) or their +refusing counterparts (`NoConditionalPutSuite`, `KeyDirectoryConflictSuite`). Every test runs twice: through `Store`, +and through an `AsyncStore` over the same backend on one event loop, so the two classes meet one +contract. + +`StoreSuite.test_state_machine` drives random sequences of `put`, `put_if_absent`, `put_if_match`, +`put_many`, `delete`, `delete_if_match`, `delete_many`, `delete_dir` and listings through random views, and checks every step against a +dict model, again through both surfaces. After every +step, each stored key reads back as the model says, through `get` and `get_many`, and +`get_if_changed` with its generation is `Unchanged`. The obstore +tests also fail any async run that makes a blocking obstore call. + +## Contexts + +Resource limits are part of a store's context, as in TensorStore. zarrs has no I/O limits of its +own (its per-call `Resources` carry only a compute target, from Rayon's global pool); it bounds +object-store requests by wrapping the store in object_store's `LimitStore` and sharing that store. + +- A **`Context`** holds a `ThreadPool` and a `Limiter` per resource key. It is immutable; + `ctx.child(threads=..., limits={...})` overrides some resources and takes the rest from its + parent, and a context with no parent takes the rest from the process-wide defaults + (`Context.default()`): `ThreadPool.default()` of `max(4, cpu_count)` threads (TensorStore's + `file_io_concurrency` default) and one `Limiter(32)` per resource key (its + `s3_request_concurrency` default). A default is shared state, but it changes only speed, never + what an operation does. +- **Every view carries a context**, `Context.default()` unless given one (`Store(backend, + context=...)`, `store.with_context(ctx)`). Every operation the view runs holds a slot of + `context.limiter(backend.resource_key)`; blocking work (a sync backend called through an + `AsyncStore`, and the operations of a `Store` batch) runs on `context.threads`. A backend's + native batch method is handed the context and draws on its resources itself. Stores sharing a + context share its limits, whatever their backends. Like TensorStore's, a context is not part of a + store's identity: `shares_backend` and `overlaps` ignore it. +- **`store.limited(n)`** is a view whose operations, together, run at most `n` at once, for a burst + of work: its context is a child whose limiter for the backend's key is `Limiter(n, within=...)` + the parent's. A limiter `within` another holds a slot of both, so a scoped limit never exceeds the + limit it narrows. Here the design departs from TensorStore, where a child context's resource + replaces the parent's: replacing would let a scoped limit escape the process-wide one. +- **Slots are taken innermost first**, so work queued on a narrow limit holds none of the wide one, + and **where the work runs**: a sync backend's operation called through an `AsyncStore` takes its + slot on the pool thread that runs it. No operation holds a slot while it waits for a thread, so + pool threads waiting for slots and slot holders waiting for threads can't block each other. (A + draft that took slots before handing work to the pool deadlocked once a pool thread itself + needed a slot: a sync `Store` used on a pool thread, or a backend that delegates to a `Store`.) +- **Cancellation**: an `AsyncStore` operation cancelled before it starts, or while its pool thread + waits for its slot, never runs, provided the cancellation reaches it before the slot does. One + already running finishes on its thread, as with `run_in_executor`. +- `limiter.slot()` is a sync or async context manager, and a slot is not re-entrant, as with a lock: + stores take exactly one slot per operation, and never call each other while holding one. An + earlier draft made slots re-entrant through a context variable; that leaked into every task and + thread inheriting the context (`asyncio.gather`, and new threads on free-threaded Python 3.14), + letting a fan-out run unbounded under one slot. +- A batch started on one of its pool's own threads runs on that thread, one operation at a time, + and so does an `AsyncStore` operation awaited on one (an event loop running inside the pool's + work): waiting there for work queued on the same pool could wait forever once every thread does + it. +- Whoever creates a resource owns it; the default pool can't be shut down. Pickling a context + pickles its resources' settings, and pickle stores each object once, so stores that shared a + context or a resource share one after a round trip; a default unpickles as the receiving + process's default. +- Pools for I/O and for compute should stay separate (TensorStore's `file_io_concurrency` and + `data_copy_concurrency`): compute waiting on I/O in one pool starves it. A context holds the I/O + pool; zarr-python's codec pipeline would take its own. + +## Caching + +Planned for iteration 3; not built yet. A cache is a resource of the store's context, like +TensorStore's `cache_pool`. It is neither a store class that wraps another store (zarr-python's +`CacheStore`) nor a hook on store methods: + +- **A wrapper can't get its capabilities right.** A Python class can't have exactly the capabilities + of the backend it wraps. It would need one class per combination, or it would claim every + capability and raise at runtime, losing the typed capabilities. +- **A hook that caches is a wrapper.** To serve a hit, a hook has to skip the read and supply the + result, and then it is a wrapper. + +The rule: wrapping is for layers that change what keys mean (zip, sharding). Policies that leave +the meaning alone (limits, caching, retries) are context resources. + +- **A `CachePool(tier, total_bytes)` is a context resource**, set with `Context(cache=...)` or + `ctx.child(cache=...)`. The default pool holds 0 bytes, so caching is off until a context gives it + a budget. Stores sharing a context share its pool: one byte budget, one eviction order. +- **The cached bytes live in a store, the tier.** The tier is a memory store by default, a local + store for a disk cache, or any other writable store. Each cached value is a value in the tier, so + the cache gets the following from the tier without new code: + - byte-range reads and `get_ranges`, served from one cached whole value; + - batches, for the hits of a batch; + - thread safety and both surfaces (a memory tier answers an `AsyncStore` inline); + - the conformance suite, as the tier's tests. + + zarr-python's `CacheStore` keeps its bytes in a store too; what changes is where the cache sits. +- **A cache is more than a store.** Beside the tier, the pool keeps an index in memory for what a + store can't hold. Per entry, the index records: + - the source's generation (the tier mints its own); + - the source's `read_at`; + - the entry's size and recency; + - absences: a `Missing` from the source has no bytes to store. + + The index also runs eviction, and it combines concurrent misses on one key into one source read. +- **Tier keys are opaque and written once.** The index names each entry's bytes with a fresh key + under a random per-pool prefix. Tier keys don't come from source keys, because the key grammar + has no way to name the source backend. A refresh writes a new key and points the index at it. + Eviction removes the index entry, then deletes the key. So no reader sees a tier value change + under it, and a tier read that returns `Missing` (evicted, or a disk tier someone else cleaned) is + a miss. Pools sharing a disk tier don't collide. +- **Entries are keyed by backend instance and path**, the identity `shares_backend` uses. Closing a + backend drops its entries. +- **Each view decides how stale a read may be**, with `store.with_max_age(seconds)`, default `0`. + TensorStore makes the same split (`recheck_cached_metadata`, `recheck_cached_data`), because + metadata and chunks need different answers. + - A hit younger than `max_age` returns without touching the source. + - An older hit revalidates with `get_if_changed(key, generation)`. On object stores that's a + conditional GET: one round trip, no bytes. + - `math.inf` trusts the cache forever, for values that are never rewritten. + - An absence ages like a value, but only a full read can revalidate it, so caching absences pays + only when `max_age > 0`: zarr's metadata probes for format versions, for example. +- **Writes keep a pool coherent.** A write or delete through a view whose context holds the pool + drops that key's entry, and `delete_dir` drops every entry under its prefix. Writes also bump a + per-key epoch, and a read that started before a write to its key returns its result but + doesn't fill the cache. So a view + sees its pool's own writes whatever its `max_age`. Writes from other processes, other pools, or + straight to the backend show up only through revalidation, as in TensorStore. +- **Hits hold no source slot.** The tier runs under a context of the pool's own, so a hit waits on + neither the source's limiter nor the process-wide `memory` limiter. A revalidation or a miss holds + a source slot like any other read. +- Listings are never cached, and neither is a value larger than the budget. +- Pickling a pool pickles its budget and its tier's configuration, never its contents. The + receiver starts with an empty index and an empty tier. +- `get_into` into a buffer type the tier can't write (device memory, with a host tier) bypasses + the pool. +- Every `StoreSuite` runs again through a cached view (a pool with a budget, `max_age=0`), where the + cache must be invisible. The state machine adds writes made straight to the backend, which only + revalidation can catch. + +## Memory-mapped reads and range writes + +Planned; not built yet. Both are new capabilities, so nothing existing changes. Neither is a +keyword on an existing method or backend, because each changes a contract, not just speed. + +**Memory-mapped reads.** `LocalBackend` never changes a file in place: a write stages a new file +and renames it over the old name, and a delete unlinks. So a mapping of a key's file is a snapshot +of one generation. A later write gives the name a new inode while the mapping keeps the old one, a +delete leaves the inode alive while it is mapped, and the generation, taken by `fstat` on the mapped +descriptor, names exactly the mapped bytes. + +- A sync capability `Mappable` with `map(path) -> Mapped | Missing`. `Mapped` is a frozen result + holding `value` (a `memoryview` over the mapping), `generation` and `read_at`, with `close()` and + `with` to release the mapping when the caller is done. `Store.map(key)` exists only on + `Store[Mappable]`; `AsyncStore.map` makes the mapping on the context's pool. +- It is not what `get` returns, because a mapped view does its I/O later, when pages are touched, + on whatever thread touches them: through `AsyncStore`, that would be the event loop's thread, + while decoding. A mapping also holds a descriptor and address space for as long as anyone holds + the view. The method's name says both. +- No fallback to a whole read: that changes when I/O happens and adds a copy, which is a change of + behavior, not only of speed (see the fallback rule under Operations). +- Where it pays: uncompressed chunks viewed without a copy (`numpy.frombuffer`), and several + ranges of a large shard sliced from one mapping. For small values a read is faster, and an empty + file can't be mapped. +- Not on Windows, where a mapped file can't be replaced or deleted: one reader holding a mapping + would make every write of that key fail. + +**Range writes.** Writing part of a value has two designs with different guarantees. + +- **Copy-on-write** (planned): a `WritableRange` capability with `put_range(key, offset, value)` + that copies the value into staging, patches the range, and renames into place under the + directory's lock, as `put` does, with `if_match` variants as for `put`. Atomic replacement, unique + generations, mapped snapshots and single-generation `get_ranges` all still hold. The copy costs + the whole value, except where the filesystem clones files: then the copy shares the original's + blocks, and only the blocks the patch touches are written. APFS (`clonefile`) and Btrfs, XFS and + bcachefs (`FICLONE`) clone; ext4 and NTFS don't, and there the copy is a full copy. +- **In place** (not planned): `pwrite` into the existing file. Fast, but it weakens what other + operations of the same backend promise: readers can see a torn value, `get_ranges` can return + parts from different moments under one generation, and a mapped reader sees bytes change under + it. Such writes would still have to hold the directory's lock and stamp a new mtime, or + conditional operations would compare equal generations of different bytes. Because the contract + changes for the whole store, this would be a separate backend type with its own documented + guarantees, not a method of `LocalBackend`, and only if a use case needs it: rewriting one inner + chunk of a large shard is the likely one, and clones make copy-on-write cheap there. +- Object stores can't write part of a value (S3 has no partial PUT), so `WritableRange` is a local + capability, and calling `put_range` on a store over obstore is a type error. + +## Configuration + +No global configuration. Every knob is a constructor parameter with its default in the signature; +resources are passed in a store's context. No parameter decides whether constructing something +changes external state: that is a constructor of its own (`LocalBackend.create`), so a call that +creates a directory reads as one. + +## Open + +- Durability: no backend syncs to disk; a `sync` option on `LocalBackend` would. +- Staged files left by a crash are never read but are never removed either. +- Windows rules are implemented and unit-tested, not yet run on Windows. There, `delete_dir` walks + by path, so a directory swapped for a junction or symlink mid-walk can still be followed. +- Listings hold no slot of the context's limiter. +- A write to a `LocalBackend` whose root is gone recreates the root and every missing directory + above it, so after the volume holding the root is unmounted, writes rebuild its path on the + filesystem below. Recording the root's device and refusing to create directories on another one + would stop that, but every directory a write creates would have to go through the check, with the + same retries for a concurrent `delete_dir` as today (EINVAL as well as ENOENT on macOS), and a + pickled backend's device number means nothing on another machine. A first attempt at it failed + review for exactly those races. +- `delete_dir` holds two descriptors per directory level while it walks (the directory and its + lock), so a tree about 125 levels deep exhausts macOS's default limit of 256. +- A derived view pickled without its owner restores as a view whose backend copy nothing owns; + `view.backend.close()` closes it. +- A burst through a narrowly limited view of a sync backend (`limited(1)`) can occupy every thread + of a shared pool, each waiting for that view's slot, so other stores on the pool wait behind the + burst. That is the cost of taking slots on pool threads (above); a pool per limiter, or slot-aware + dispatch, would remove it. +- An `AsyncStore` batch makes its window of tasks at once; after a failure, those still waiting for a + slot run anyway (a `Store` batch cancels its queued ones). +- A slot granted to a task whose event loop then closes without running it again is lost. +- Case-insensitive filesystems (APFS, NTFS) store distinct keys such as `a` and `A` in one file, and + APFS does the same for differently normalized Unicode names, under `LocalBackend` and obstore's `LocalStore` alike. +- `ObjectStoreBackend` passes obstore's own errors through for keys the grammar allows and obstore + refuses (control characters; on its `LocalStore`, names ending in `#` and digits). +- `get_ranges_into`, `put_from`, and a GPU direct storage backend whose `get_into_many` submits one + cuFile batch. +- Caching: range reads of values the pool doesn't hold whole go to the source. Shard indexes are the + case that matters, and they belong to the codec pipeline, not here: the sharding codec knows where + an index is and can cache it decoded, keyed by store, key and generation. The storage layer gives + it what it needs: the generation of every read, and `get_if_changed` with a byte range to + revalidate one. +- Caching: a disk tier starts cold in every process, because the index lives in memory. +- Caching: a pool over a memory backend copies values for no gain; nothing stops one yet. + +## Iterations + +1. **Core:** types, `Store`, the memory and local backends, the conformance suite in + `zarr_storage.experimental.testing`, pickling. +2. **Remote and archive backends:** obstore (S3, GCS, Azure, HTTP; async-native), fsspec, zip. +3. **Composition:** range coalescing, caching (see Caching), retry, a sync bridge for async-only backends, URL specs. +4. **Transactions:** staged writes committed with generations, memory first. diff --git a/packages/zarr-storage/README.md b/packages/zarr-storage/README.md index 6b3f62e63e..906541ef50 100644 --- a/packages/zarr-storage/README.md +++ b/packages/zarr-storage/README.md @@ -8,6 +8,12 @@ store API is developed memory, local files, zip files, fsspec and obstore. The module `zarr.X` is `zarr_storage.legacy.X`. The package does not depend on `zarr`. +`zarr_storage.experimental` is the API meant to succeed it: sync and async stores +over memory, local-filesystem and object-store backends, with conditional writes, +byte-range reads, batches, and a conformance suite any backend can run. Any +release may change it. [`DESIGN.md`](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-storage/DESIGN.md) +describes it. + Use `zarr.storage` with `zarr` for now. Until `zarr` depends on this package, `zarr_storage.legacy` is a copy with classes of its own, and `zarr` does not accept its stores. It reads zarr's entry-point groups, so a URL pipeline adapter or @@ -17,8 +23,9 @@ buffer class written for `zarr` doesn't work with it yet either. pip install zarr-storage ``` -The `remote` extra adds fsspec and obstore, and the `testing` extra adds what the -store conformance suite needs. +The `remote` extra adds fsspec and obstore for the legacy stores, the `obstore` +extra adds the newer obstore that the experimental API needs, and the `testing` +extra adds what the conformance suites need. - Documentation: https://zarr-storage.readthedocs.io/ - Changelog: [`CHANGELOG.md`](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-storage/CHANGELOG.md) diff --git a/packages/zarr-storage/changes/0001.feature.md b/packages/zarr-storage/changes/0001.feature.md new file mode 100644 index 0000000000..025b9212cb --- /dev/null +++ b/packages/zarr-storage/changes/0001.feature.md @@ -0,0 +1 @@ +Add `zarr_storage.experimental`, the store API meant to succeed `zarr_storage.legacy`: `Store` and `AsyncStore` views over memory, local-filesystem and obstore backends, with the same operations as sync methods and as coroutines, conditional reads and writes, byte-range reads, reads into caller buffers, batches, and contexts that hold thread pools and limits. `zarr_storage.experimental.testing` has a conformance suite that any backend can run. Any release may change this API. diff --git a/packages/zarr-storage/docs/api/experimental.md b/packages/zarr-storage/docs/api/experimental.md new file mode 100644 index 0000000000..7adb2df96c --- /dev/null +++ b/packages/zarr-storage/docs/api/experimental.md @@ -0,0 +1,5 @@ +--- +title: experimental +--- + +::: zarr_storage.experimental diff --git a/packages/zarr-storage/docs/api/experimental_backends.md b/packages/zarr-storage/docs/api/experimental_backends.md new file mode 100644 index 0000000000..52ed406e23 --- /dev/null +++ b/packages/zarr-storage/docs/api/experimental_backends.md @@ -0,0 +1,5 @@ +--- +title: experimental.backends +--- + +::: zarr_storage.experimental.backends diff --git a/packages/zarr-storage/docs/api/experimental_testing.md b/packages/zarr-storage/docs/api/experimental_testing.md new file mode 100644 index 0000000000..8d5d3b08d9 --- /dev/null +++ b/packages/zarr-storage/docs/api/experimental_testing.md @@ -0,0 +1,5 @@ +--- +title: experimental.testing +--- + +::: zarr_storage.experimental.testing diff --git a/packages/zarr-storage/docs/api/index.md b/packages/zarr-storage/docs/api/index.md index e1d8f657e0..554e3f8c9c 100644 --- a/packages/zarr-storage/docs/api/index.md +++ b/packages/zarr-storage/docs/api/index.md @@ -8,3 +8,11 @@ title: API reference its stores. - [`zarr_storage.legacy.testing`](legacy_testing.md): the conformance suite a store implementation runs (needs the `testing` extra). +- [`zarr_storage.experimental`](experimental.md): `Store` and `AsyncStore`, the + result types, byte-range requests, errors, the capability protocols a backend + implements, and `Context` with its resources. +- [`zarr_storage.experimental.backends`](experimental_backends.md): + `MemoryBackend`, `LocalBackend`, and `ObjectStoreBackend` (needs the `obstore` + extra). +- [`zarr_storage.experimental.testing`](experimental_testing.md): the conformance + suite a backend runs (needs the `testing` extra). diff --git a/packages/zarr-storage/docs/design.md b/packages/zarr-storage/docs/design.md new file mode 100644 index 0000000000..0afb51cd34 --- /dev/null +++ b/packages/zarr-storage/docs/design.md @@ -0,0 +1,4 @@ + + +--8<-- "DESIGN.md" diff --git a/packages/zarr-storage/docs/experimental.md b/packages/zarr-storage/docs/experimental.md new file mode 100644 index 0000000000..5c7fac555a --- /dev/null +++ b/packages/zarr-storage/docs/experimental.md @@ -0,0 +1,60 @@ +# The experimental API + +`zarr_storage.experimental` is a key-value storage layer that knows nothing about +the Zarr format: it stores and lists values under `/`-separated keys, and leaves +arrays, groups and metadata documents to the Zarr implementation built on it. It +is meant to succeed `zarr_storage.legacy`. + +!!! warning "Experimental" + Any release may change this API. `zarr` doesn't use it yet. + +The `obstore` extra adds `ObjectStoreBackend` (S3, GCS, Azure, HTTP and more, +through [obstore](https://developmentseed.org/obstore/)), and the `testing` +extra adds the conformance suite. + +## Quickstart + +A `Store` is a view of a backend at a root directory. Results are small frozen +types, one per outcome, so a `match` handles each: + +```python +from zarr_storage.experimental import Found, Missing, Store +from zarr_storage.experimental.backends import MemoryBackend + +store = Store(MemoryBackend()) +store.put("data/a", b"hello") +match store.get("data/a"): + case Found(value=value): + print(bytes(value)) # b'hello' + case Missing(): + print("absent") + +sub = store / "data" # a view on the same backend +print(list(sub.list())) # ['a'] +``` + +Conditional operations are separate methods that report a refusal instead of +raising: + +```python +found = store.get("data/a") +store.put_if_absent("data/a", b"again") # Rejected(...) +store.put_if_match("data/a", b"new", found.generation) # Written(...) +``` + +`AsyncStore` has the same methods as coroutines, and `store.as_async()` is an +`AsyncStore` view on the same backend: + +```python +astore = store.as_async() +await astore.put("x", b"1") +print(await astore.get("x")) +``` + +The store that was constructed owns its backend: `store.close()` (or a `with` +block) closes it, and closing a view such as `sub` or `astore` does nothing. + +## Where to go next + +- [Design](design.md): the contract every backend and store meets. +- [API reference](api/index.md). diff --git a/packages/zarr-storage/docs/index.md b/packages/zarr-storage/docs/index.md index 42473a9457..3ad8f0f096 100644 --- a/packages/zarr-storage/docs/index.md +++ b/packages/zarr-storage/docs/index.md @@ -22,7 +22,8 @@ pip install zarr-storage ``` The `remote` extra adds fsspec and obstore, for `FsspecStore` and `ObjectStore`. -The `testing` extra adds what the store conformance suite needs. +The `obstore` extra adds the newer obstore that the experimental API needs. The +`testing` extra adds what the conformance suites need. ## Use @@ -43,4 +44,6 @@ async def main() -> None: asyncio.run(main()) ``` -See the [API reference](api/index.md). +The next store API is being developed in +[`zarr_storage.experimental`](experimental.md). See also the +[API reference](api/index.md). diff --git a/packages/zarr-storage/justfile b/packages/zarr-storage/justfile index 744f547101..aedf8ba685 100644 --- a/packages/zarr-storage/justfile +++ b/packages/zarr-storage/justfile @@ -51,9 +51,10 @@ test-versions *args: lint: uvx ruff@{{ ruff_version }} check . -# Type-check the package sources +# Type-check the package: the legacy code with mypy, as zarr does, the rest with pyright typecheck: uv run --python 3.12 --group test --with mypy=={{ mypy_version }} mypy + uv run --python 3.12 --group test --with pyright pyright # Copy the store code of `src/zarr` to `zarr_storage.legacy`; with --check, only report differences sync-legacy *args: diff --git a/packages/zarr-storage/mkdocs.yml b/packages/zarr-storage/mkdocs.yml index aad513b35e..3befc15761 100644 --- a/packages/zarr-storage/mkdocs.yml +++ b/packages/zarr-storage/mkdocs.yml @@ -20,10 +20,15 @@ validation: nav: - index.md + - The experimental API: experimental.md + - Design: design.md - API Reference: - api/index.md - ' zarr_storage.legacy': api/legacy.md - ' zarr_storage.legacy.testing': api/legacy_testing.md + - ' zarr_storage.experimental': api/experimental.md + - ' zarr_storage.experimental.backends': api/experimental_backends.md + - ' zarr_storage.experimental.testing': api/experimental_testing.md - Release notes: release-notes.md # This site is a Read the Docs subproject of zarr-python; give readers a way # back to the parent docs, which list every companion package. diff --git a/packages/zarr-storage/pyproject.toml b/packages/zarr-storage/pyproject.toml index 8cb4864b56..20469d2386 100644 --- a/packages/zarr-storage/pyproject.toml +++ b/packages/zarr-storage/pyproject.toml @@ -40,7 +40,9 @@ dependencies = [ [project.optional-dependencies] # `FsspecStore` and `ObjectStore`, with zarr's floors. remote = ["fsspec>=2023.10.0", "obstore>=0.5.1"] -# The `zarr_storage.legacy.testing` conformance suite. +# `zarr_storage.experimental.backends.ObjectStoreBackend`. +obstore = ["obstore>=0.12"] +# The conformance suites in `zarr_storage.legacy.testing` and `zarr_storage.experimental.testing`. testing = ["pytest>=9", "pytest-asyncio>=1.0", "hypothesis>=6.160"] [project.entry-points.pytest11] @@ -58,7 +60,7 @@ test = [ "pytest>=9", "pytest-asyncio>=1.0", "fsspec>=2023.10.0", - "obstore>=0.5.1", + "obstore>=0.12", "universal-pathlib", "hypothesis>=6.160", # `FsspecStore` against a mock S3 server. @@ -102,6 +104,7 @@ include = [ "/mkdocs.yml", "/justfile", "/CHANGELOG.md", + "/DESIGN.md", ] # The shared docs config and header script are symlinks out of the package # directory in the repository; ship the files they point at, since a link out @@ -116,15 +119,26 @@ exclude = ["/mkdocs-base.yml", "/docs/_static/source-version.js"] extend = "../../pyproject.toml" target-version = "py312" -# As zarr's own tests, which these are copies of. +[tool.ruff.lint] +# Use `object` for "any value"; a genuinely dynamic annotation needs a noqa +# saying why. The legacy code is zarr's, which doesn't have this rule. +extend-select = ["ANN401"] + [tool.ruff.lint.extend-per-file-ignores] -"tests/legacy/**" = ["ANN001", "ANN201", "E402", "SIM117"] +"src/zarr_storage/legacy/**" = ["ANN401"] +# Written with `TypeVar`s: `Store` is covariant in its backend, and its methods' `self` types share +# the variables. +"src/zarr_storage/experimental/**" = ["UP046", "UP047"] +# As zarr's own tests, which these are copies of. +"tests/legacy/**" = ["ANN001", "ANN201", "ANN401", "E402", "SIM117"] [tool.pytest.ini_options] minversion = "9" testpaths = ["tests"] strict = true addopts = ["-ra", "--import-mode=importlib"] +# So processes that tests spawn can import the test modules. +pythonpath = ["."] asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "function" faulthandler_timeout = 600 @@ -143,9 +157,30 @@ markers = [ "s3: mark a test as requiring a (mock) S3 backend via moto", ] -# The root configuration: the code is zarr's, checked there with mypy. +# Pyright checks the experimental API. The legacy code is zarr's, and is checked with mypy, as it +# is there. +[tool.pyright] +include = ["src/zarr_storage/experimental", "tests/experimental"] +enableTypeIgnoreComments = false +reportUnnecessaryTypeIgnoreComment = "error" +extraPaths = ["."] +typeCheckingMode = "strict" +pythonVersion = "3.12" + +[[tool.pyright.executionEnvironments]] +root = "tests" +reportMissingTypeArgument = false +reportPrivateUsage = false +reportUnknownArgumentType = false +reportUnknownLambdaType = false +reportUnknownMemberType = false +reportUnknownParameterType = false +reportUnknownVariableType = false +reportUnusedFunction = false + +# The root configuration. [tool.mypy] -files = ["src"] +files = ["src/zarr_storage/__init__.py", "src/zarr_storage/_pytest_plugin.py", "src/zarr_storage/legacy"] python_version = "3.12" ignore_missing_imports = true namespace_packages = false diff --git a/packages/zarr-storage/src/zarr_storage/__init__.py b/packages/zarr-storage/src/zarr_storage/__init__.py index 38bdf1c8a9..4225de2c54 100644 --- a/packages/zarr-storage/src/zarr_storage/__init__.py +++ b/packages/zarr-storage/src/zarr_storage/__init__.py @@ -1,6 +1,7 @@ """Storage for Zarr implementations. `zarr_storage.legacy` holds the store API of zarr-python 3 and its stores. +`zarr_storage.experimental` holds the API meant to succeed it; it may change in any release. """ from importlib.metadata import version diff --git a/packages/zarr-storage/src/zarr_storage/experimental/__init__.py b/packages/zarr-storage/src/zarr_storage/experimental/__init__.py new file mode 100644 index 0000000000..1bb78a63ed --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/__init__.py @@ -0,0 +1,122 @@ +"""A Zarr-agnostic key-value storage layer. + +A `Store` is a view of a backend at a root directory, used through sync methods; an `AsyncStore` +is the same view used through coroutines, with the same method names. Backends implement capability +protocols (`Readable`, `Writable`, `Listable`, their batch variants, and async twins) over backend +paths; the stores validate keys, apply their root, enforce read-only access, schedule and limit +operations with the resources of their `Context`, and are the only objects most callers need. + +This API is experimental: any release may change it. +""" + +from zarr_storage.experimental._errors import ( + BatchError, + InvalidByteRangeError, + InvalidKeyError, + KeyConflictError, + ReadOnlyError, + StorageError, + StoreClosedError, + UnsupportedOperationError, +) +from zarr_storage.experimental._protocols import ( + Backend, + ClosableAsync, + DeletableIfMatch, + DeletableIfMatchAsync, + Listable, + ListableAsync, + Readable, + ReadableAsync, + ReadableInto, + ReadableIntoAsync, + ReadableIntoMany, + ReadableIntoManyAsync, + ReadableMany, + ReadableManyAsync, + Writable, + WritableAsync, + WritableIfMatch, + WritableIfMatchAsync, + WritableMany, + WritableManyAsync, +) +from zarr_storage.experimental._resources import Context, Limiter, Slot, ThreadPool +from zarr_storage.experimental._store import AsyncStore, Store +from zarr_storage.experimental._types import ( + ByteRange, + Copied, + Deleted, + Entry, + Found, + FoundRanges, + Generation, + Key, + ListItem, + Location, + Missing, + ObjectMetadata, + OffsetRequest, + Prefix, + RangeRequest, + Rejected, + SuffixRequest, + Unchanged, + Written, +) + +__all__ = [ + "AsyncStore", + "Backend", + "BatchError", + "ByteRange", + "ClosableAsync", + "Context", + "Copied", + "DeletableIfMatch", + "DeletableIfMatchAsync", + "Deleted", + "Entry", + "Found", + "FoundRanges", + "Generation", + "InvalidByteRangeError", + "InvalidKeyError", + "Key", + "KeyConflictError", + "Limiter", + "ListItem", + "Listable", + "ListableAsync", + "Location", + "Missing", + "ObjectMetadata", + "OffsetRequest", + "Prefix", + "RangeRequest", + "ReadOnlyError", + "Readable", + "ReadableAsync", + "ReadableInto", + "ReadableIntoAsync", + "ReadableIntoMany", + "ReadableIntoManyAsync", + "ReadableMany", + "ReadableManyAsync", + "Rejected", + "Slot", + "StorageError", + "Store", + "StoreClosedError", + "SuffixRequest", + "ThreadPool", + "Unchanged", + "UnsupportedOperationError", + "Writable", + "WritableAsync", + "WritableIfMatch", + "WritableIfMatchAsync", + "WritableMany", + "WritableManyAsync", + "Written", +] diff --git a/packages/zarr-storage/src/zarr_storage/experimental/_batch.py b/packages/zarr-storage/src/zarr_storage/experimental/_batch.py new file mode 100644 index 0000000000..25e15f94dd --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/_batch.py @@ -0,0 +1,124 @@ +"""Running one operation over many requests, for `Store`'s fallbacks and backends' batch methods. + +Both runners yield `(index, result)` pairs as operations finish, so callers map results back to +their requests. A runner keeps at most `window` operations in flight. After the first failure it +starts no new operations (on a pool, it cancels those still queued), lets the running ones finish (yielding those that succeed), then raises +an `ExceptionGroup` of every failure. `Store` turns that group into a `BatchError`. +""" + +from __future__ import annotations + +import asyncio +from concurrent.futures import FIRST_COMPLETED, wait +from typing import TYPE_CHECKING, Any, TypeVar, TypeVarTuple, Unpack + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Callable, Coroutine, Iterator, Sequence + from concurrent.futures import Future + + from zarr_storage.experimental._resources import ThreadPool + +__all__ = ["run_many", "run_many_async"] + +R = TypeVar("R") +Ts = TypeVarTuple("Ts") + +_MESSAGE = "Operations of a batch failed." + + +def run_many( + fn: Callable[[Unpack[Ts]], R], + requests: Sequence[tuple[*Ts]], + pool: ThreadPool | None = None, + window: int = 1, +) -> Iterator[tuple[int, R]]: + """Call `fn(*request)` for each request: one at a time, or on `pool`, `window` at once. + + Called from one of `pool`'s own threads, it runs one at a time on that thread: waiting there + for work queued behind it on the same pool could wait forever. + """ + if pool is None or pool.in_worker(): + return _run_serially(fn, requests) + return _run_on(pool, fn, requests, window) + + +def _run_serially( + fn: Callable[[Unpack[Ts]], R], requests: Sequence[tuple[*Ts]] +) -> Iterator[tuple[int, R]]: + for index, request in enumerate(requests): + try: + result = fn(*request) + except Exception as error: # noqa: BLE001 -- every failure is reported, in the group + raise ExceptionGroup(_MESSAGE, [error]) from None + yield index, result + + +def _run_on( + pool: ThreadPool, + fn: Callable[[Unpack[Ts]], R], + requests: Sequence[tuple[*Ts]], + window: int, +) -> Iterator[tuple[int, R]]: + pending: dict[Future[R], int] = {} + errors: list[Exception] = [] + started = 0 + try: + while pending or (not errors and started < len(requests)): + while not errors and started < len(requests) and len(pending) < window: + pending[pool.submit(fn, *requests[started])] = started + started += 1 + done, _ = wait(pending, return_when=FIRST_COMPLETED) + for future in done: + index = pending.pop(future) + error = future.exception() + if error is None: + yield index, future.result() + elif isinstance(error, Exception): + errors.append(error) + else: + raise error + if errors: + _cancel_queued(pending) + finally: + _cancel_queued(pending) + if errors: + raise ExceptionGroup(_MESSAGE, errors) + + +def _cancel_queued(pending: dict[Future[R], int]) -> None: + """Drop the operations in `pending` that haven't started; those running stay.""" + for future in [future for future in pending if future.cancel()]: + del pending[future] + + +async def run_many_async( + fn: Callable[[Unpack[Ts]], Coroutine[Any, Any, R]], + requests: Sequence[tuple[*Ts]], + window: int = 1, +) -> AsyncIterator[tuple[int, R]]: + """Await `fn(*request)` for each request, `window` at once.""" + pending: dict[asyncio.Task[R], int] = {} + errors: list[Exception] = [] + started = 0 + try: + while pending or (not errors and started < len(requests)): + while not errors and started < len(requests) and len(pending) < window: + pending[asyncio.ensure_future(fn(*requests[started]))] = started + started += 1 + done, _ = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) + for task in done: + index = pending.pop(task) + error = task.exception() + if error is None: + yield index, task.result() + elif isinstance(error, Exception): + errors.append(error) + else: + raise error + finally: + for task in pending: + task.cancel() + if pending: + await asyncio.gather(*pending, return_exceptions=True) + if errors: + raise ExceptionGroup(_MESSAGE, errors) diff --git a/packages/zarr-storage/src/zarr_storage/experimental/_buffers.py b/packages/zarr-storage/src/zarr_storage/experimental/_buffers.py new file mode 100644 index 0000000000..0d80e4b32a --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/_buffers.py @@ -0,0 +1,41 @@ +"""Host-memory buffers: the byte views stores take values as, and copying a read into one.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from zarr_storage.experimental._types import Copied, Found, Missing + +if TYPE_CHECKING: + from collections.abc import Buffer + +__all__ = ["byte_view", "copy_into"] + + +def byte_view(value: Buffer, *, writable: bool) -> memoryview: + """A flat, C-contiguous byte view of a buffer. + + Raises `ValueError` if the buffer is not C-contiguous, or if `writable` and it is read-only. + """ + view = memoryview(value) + if not view.c_contiguous: + raise ValueError("The buffer must be C-contiguous.") + if writable and view.readonly: + raise ValueError("The output buffer must be writable.") + return view.cast("B") if view.format != "B" or view.ndim != 1 else view + + +def copy_into(result: Found | Missing, out: memoryview) -> Copied | Missing: + """The `get_into` outcome of a `get`, copying a found value into `out`. + + For a backend that can't read into a buffer directly. + """ + match result: + case Found(value=value, generation=generation, read_at=read_at): + n = len(value) + if n > len(out): + raise ValueError(f"The output buffer holds {len(out)} bytes; the value has {n}.") + out[:n] = value + return Copied(n, generation, read_at) + case Missing(): + return result diff --git a/packages/zarr-storage/src/zarr_storage/experimental/_byte_range.py b/packages/zarr-storage/src/zarr_storage/experimental/_byte_range.py new file mode 100644 index 0000000000..070cc4bce8 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/_byte_range.py @@ -0,0 +1,38 @@ +"""Resolving a byte range against the size of a value.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from zarr_storage.experimental._errors import InvalidByteRangeError +from zarr_storage.experimental._types import OffsetRequest, RangeRequest, SuffixRequest + +if TYPE_CHECKING: + from zarr_storage.experimental._types import ByteRange + +__all__ = ["resolve"] + + +def resolve(byte_range: ByteRange | None, size: int) -> tuple[int, int]: + """The `(start, end)` a byte range covers in a value of `size` bytes. + + An end past the value is clamped to `size`. A start past the value raises + `InvalidByteRangeError`; a start equal to `size` selects nothing. + """ + match byte_range: + case None: + return 0, size + case RangeRequest(start=start, end=end): + if start > size: + raise InvalidByteRangeError( + f"The range starts at byte {start}, past the end of a {size}-byte value." + ) + return start, min(end, size) + case OffsetRequest(start=start): + if start > size: + raise InvalidByteRangeError( + f"The range starts at byte {start}, past the end of a {size}-byte value." + ) + return start, size + case SuffixRequest(length=length): + return max(size - length, 0), size diff --git a/packages/zarr-storage/src/zarr_storage/experimental/_errors.py b/packages/zarr-storage/src/zarr_storage/experimental/_errors.py new file mode 100644 index 0000000000..fb47ea55d1 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/_errors.py @@ -0,0 +1,90 @@ +"""The errors a store raises. A missing key is not one of them: reads return `Missing`.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Self + +if TYPE_CHECKING: + from collections.abc import Sequence + +__all__ = [ + "BatchError", + "InvalidByteRangeError", + "InvalidKeyError", + "KeyConflictError", + "ReadOnlyError", + "StorageError", + "StoreClosedError", + "UnsupportedOperationError", +] + + +class StorageError(Exception): + """Base class for every error this package raises.""" + + +class InvalidKeyError(StorageError, ValueError): + """A key or directory does not follow the key grammar, or names something the backend reserves.""" + + +class InvalidByteRangeError(StorageError, ValueError): + """A byte range starts past the end of the value it reads.""" + + +class KeyConflictError(StorageError): + """A key collides with a directory of the same name on a backend that can't hold both. + + Object stores and in-memory stores hold `a` and `a/b` side by side; a filesystem can't. + """ + + +class ReadOnlyError(StorageError): + """A write was attempted through a read-only store.""" + + +class StoreClosedError(StorageError): + """An operation was attempted after the store's backend was closed.""" + + +class UnsupportedOperationError(StorageError, NotImplementedError): + """The store's backend does not implement the requested operation.""" + + +class BatchError(ExceptionGroup[Exception], StorageError): + """Some operations of a batch (`get_many`, `put_many`, ...) raised. + + After the first failure a batch starts no new operations; the ones already running finish. The + group holds every exception those operations raised. `completed` pairs each request that + finished with its result, and `remaining` holds the requests that failed or never started: a + write among them may or may not have landed. + """ + + completed: tuple[tuple[object, object], ...] + remaining: tuple[object, ...] + + def __new__( + cls, + message: str, + exceptions: Sequence[Exception], + *, + completed: tuple[tuple[object, object], ...], + remaining: tuple[object, ...], + ) -> Self: + self = super().__new__(cls, message, exceptions) + self.completed = completed + self.remaining = remaining + return self + + def __init__( + self, + message: str, + exceptions: Sequence[Exception], + *, + completed: tuple[tuple[object, object], ...], + remaining: tuple[object, ...], + ) -> None: + super().__init__(message, exceptions) + + def derive(self, excs: Sequence[Exception]) -> BatchError: # pyright: ignore[reportIncompatibleMethodOverride] -- a batch only ever holds `Exception`s + """The same batch error, holding `excs`; `except*` builds its subgroups with this.""" + return BatchError(self.message, excs, completed=self.completed, remaining=self.remaining) diff --git a/packages/zarr-storage/src/zarr_storage/experimental/_keys.py b/packages/zarr-storage/src/zarr_storage/experimental/_keys.py new file mode 100644 index 0000000000..97ffd91bb4 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/_keys.py @@ -0,0 +1,71 @@ +"""The key grammar, and the joins between a store's root and its keys. + +Every path operation in this package goes through these functions, so the rules live in one place. +""" + +from __future__ import annotations + +from zarr_storage.experimental._errors import InvalidKeyError + +__all__ = [ + "check_key", + "is_within", + "join", + "normalize_directory", + "relativize", +] + + +def check_key(key: str) -> str: + """Return `key` unchanged if it follows the key grammar; raise `InvalidKeyError` otherwise. + + A key is not empty, has no leading or trailing `/`, no empty segment, no `.` or `..` segment, + and no NUL character. Backends may refuse more (a filesystem refuses names it can't represent). + """ + if not isinstance(key, str): # pyright: ignore[reportUnnecessaryIsInstance] + raise InvalidKeyError(f"A key must be a str; got {type(key).__name__}.") + if key == "": + raise InvalidKeyError("A key must not be empty.") + if "\x00" in key: + raise InvalidKeyError(f"A key must not contain a NUL character; got {key!r}.") + if key.startswith("/") or key.endswith("/"): + raise InvalidKeyError(f"A key must not start or end with '/'; got {key!r}.") + for segment in key.split("/"): + if segment in ("", ".", ".."): + raise InvalidKeyError( + f"A key must not contain an empty, '.' or '..' segment; got {key!r}." + ) + return key + + +def normalize_directory(directory: str) -> str: + """Return the canonical form of a directory: `""` for the root, otherwise a key. + + A trailing `/` is accepted and removed, so `"a"` and `"a/"` name the same directory. + """ + if not isinstance(directory, str): # pyright: ignore[reportUnnecessaryIsInstance] + raise InvalidKeyError(f"A directory must be a str; got {type(directory).__name__}.") + if directory in ("", "/"): + return "" + return check_key(directory.removesuffix("/")) + + +def join(directory: str, key: str) -> str: + """Join a normalized directory and a key (or normalized directory).""" + if directory == "": + return key + if key == "": + return directory + return f"{directory}/{key}" + + +def relativize(path: str, directory: str) -> str: + """The part of `path` under the normalized `directory`. `path` must be inside it.""" + if directory == "": + return path + return path.removeprefix(f"{directory}/") + + +def is_within(path: str, directory: str) -> bool: + """Whether `path` is `directory` itself or lies under it (both normalized).""" + return directory == "" or path == directory or path.startswith(f"{directory}/") diff --git a/packages/zarr-storage/src/zarr_storage/experimental/_protocols.py b/packages/zarr-storage/src/zarr_storage/experimental/_protocols.py new file mode 100644 index 0000000000..8489b65b3f --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/_protocols.py @@ -0,0 +1,352 @@ +"""Capability protocols that backends implement. + +A backend works on *backend paths*: keys and directories already joined with a store's root and +already checked against the key grammar. A backend never joins, strips or validates paths beyond +what it reserves for itself. `Store` does all of that, once, for every backend. + +Directories are passed normalized: `""` for the backend's root, otherwise a key without a trailing +`/`. + +Each capability has a sync protocol and an async twin whose methods end in `_async`. A backend +implements whichever it can. `Store` calls the sync protocols. `AsyncStore` calls the async twin +where the backend has it and otherwise runs the sync method on its context's thread pool, so a +backend that only blocks (a filesystem) needs no async code. Methods are typed so that calling one +the backend lacks is a type error. Compare-and-swap on a generation (`WritableIfMatch`, +`DeletableIfMatch`) is a capability of its own, since many stores can't do it; `put_if_absent` is +part of `Writable`. + +Backends hold no thread pools or limits: the store schedules and limits every operation with the +resources of its `Context`, under the backend's `resource_key`. Backends must be thread-safe, since +a store runs their sync methods on many threads at once. + +The batch capabilities (`ReadableMany`, `ReadableIntoMany`, `WritableMany` and their async twins) +are for batching the store itself can do (one request for many keys, one GPU submission): without +them, `Store.get_many` and its siblings run single operations concurrently under the context's +resources. A batch method receives that context, so it can draw on the same resources; it yields +`(index, result)` pairs as operations finish and follows the failure rule of `zarr_storage.experimental._batch`. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Protocol, TypeVar, runtime_checkable + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterator, Sequence + + from zarr_storage.experimental._resources import Context + from zarr_storage.experimental._types import ( + ByteRange, + Copied, + Deleted, + Found, + FoundRanges, + Generation, + ListItem, + Location, + Missing, + ObjectMetadata, + Rejected, + Unchanged, + Written, + ) + +__all__ = [ + "Backend", + "ClosableAsync", + "DeletableIfMatch", + "DeletableIfMatchAsync", + "Listable", + "ListableAsync", + "Readable", + "ReadableAsync", + "ReadableInto", + "ReadableIntoAsync", + "ReadableIntoMany", + "ReadableIntoManyAsync", + "ReadableMany", + "ReadableManyAsync", + "Writable", + "WritableAsync", + "WritableIfMatch", + "WritableIfMatchAsync", + "WritableMany", + "WritableManyAsync", +] + + +O_contra = TypeVar("O_contra", contravariant=True) +"""The type of buffer a backend's `get_into` writes into.""" + + +class Backend(Protocol): + """What every backend provides: a lifecycle, whether it accepts writes, and the key its + operations are limited under.""" + + @property + def resource_key(self) -> str: + """The key of the `Limiter` that stores take from their context for this backend. + + Backends that should share a limit by default share a key: every obstore S3 backend uses + `"obstore.S3Store"`, so a process's S3 requests are bounded together. + """ + ... + + @property + def location(self) -> Location: + """Where the backend's keys live. Two backends whose locations overlap can see the same + keys, even as different objects (two local backends over nested directories).""" + ... + + @property + def closed(self) -> bool: + """Whether `close` has been called.""" + ... + + @property + def writable(self) -> bool: + """Whether the backend can write. A store over a backend that can't is read-only.""" + ... + + def close(self) -> None: + """Release the backend's resources. Idempotent.""" + ... + + +@runtime_checkable +class ClosableAsync(Backend, Protocol): + """A backend whose cleanup awaits something, such as closing a client session. + + `AsyncStore.aclose` awaits `aclose` on such a backend, and calls `close` on any other. + """ + + async def aclose(self) -> None: + """`close`, as a coroutine. Idempotent.""" + ... + + +class Readable(Backend, Protocol): + """Reads values and their metadata.""" + + def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + """The value at `path`, or the requested part of it.""" + ... + + def get_if_changed( + self, path: str, generation: Generation, byte_range: ByteRange | None + ) -> Found | Missing | Unchanged: + """`get`, or `Unchanged` without reading any bytes if the value has `generation`.""" + ... + + def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> FoundRanges | Missing: + """Several parts of the value at `path`, all from one generation.""" + ... + + def head(self, path: str) -> ObjectMetadata | Missing: + """The size and generation of the value at `path`.""" + ... + + +class ReadableInto(Backend, Protocol[O_contra]): + """Reads into a buffer the caller allocated, of the type the backend names. + + A backend over host memory takes any `Buffer` (`ReadableInto[Buffer]`). A backend that reads + into another device's memory, such as GPU direct storage, takes that device's buffer type + instead, and `Store.get_into` then accepts exactly that type. Where the bytes land is the + backend's business; `Copied` reports how many and from which generation. + """ + + def get_into(self, path: str, out: O_contra, byte_range: ByteRange | None) -> Copied | Missing: + """Copy the value (or part) into `out`. + + Raises `ValueError` if `out` is shorter than the bytes to copy, or can't be written. + """ + ... + + +class Writable(Backend, Protocol): + """Writes and deletes values.""" + + def put(self, path: str, value: memoryview) -> Written: + """Write `value` at `path`.""" + ... + + def put_if_absent(self, path: str, value: memoryview) -> Written | Rejected: + """Write `value` at `path` if the key holds no value.""" + ... + + def delete(self, path: str) -> Deleted | Missing: + """Delete the key at `path`. A directory is not a key.""" + ... + + def delete_dir(self, directory: str) -> None: + """Delete every key under `directory`.""" + ... + + +class WritableIfMatch(Backend, Protocol): + """Writes a value only over the generation the caller read (compare-and-swap).""" + + def put_if_match( + self, path: str, value: memoryview, generation: Generation + ) -> Written | Rejected | Missing: + """Write `value` at `path` if the key's value has `generation`.""" + ... + + +class DeletableIfMatch(Backend, Protocol): + """Deletes a value only if it still has the generation the caller read.""" + + def delete_if_match(self, path: str, generation: Generation) -> Deleted | Rejected | Missing: + """Delete the key at `path` if its value has `generation`.""" + ... + + +@runtime_checkable +class ReadableMany(Backend, Protocol): + """Reads many values in one batch, beyond what single reads can do (one request for many + keys); `Store.get_many` uses it instead of running single reads.""" + + def get_many( + self, requests: Sequence[tuple[str, ByteRange | None]], context: Context + ) -> Iterator[tuple[int, Found | Missing]]: + """`get` for each `(path, byte_range)`, yielding `(index, result)` as each finishes.""" + ... + + +@runtime_checkable +class ReadableIntoMany(Backend, Protocol[O_contra]): + """Reads many values into caller buffers in one batch (one GPU submission, say); + `Store.get_into_many` uses it instead of running single reads.""" + + def get_into_many( + self, requests: Sequence[tuple[str, O_contra, ByteRange | None]], context: Context + ) -> Iterator[tuple[int, Copied | Missing]]: + """`get_into` for each `(path, out, byte_range)`, yielding `(index, result)`.""" + ... + + +@runtime_checkable +class WritableMany(Backend, Protocol): + """Writes or deletes many values in one batch; `Store.put_many` and `Store.delete_many` + use it instead of running single writes.""" + + def put_many( + self, requests: Sequence[tuple[str, memoryview]], context: Context + ) -> Iterator[tuple[int, Written]]: + """`put` for each `(path, value)`, yielding `(index, result)` as each finishes.""" + ... + + def delete_many( + self, paths: Sequence[str], context: Context + ) -> Iterator[tuple[int, Deleted | Missing]]: + """`delete` for each path, yielding `(index, result)` as each finishes.""" + ... + + +class Listable(Backend, Protocol): + """Lists keys and directories.""" + + def list(self, directory: str) -> Iterator[str]: + """Every key under `directory`, as backend paths, in no particular order.""" + ... + + def list_dir(self, directory: str) -> Iterator[ListItem]: + """The direct children of `directory`, named relative to it.""" + ... + + +@runtime_checkable +class ReadableAsync(Backend, Protocol): + """`Readable`, as coroutines. `AsyncStore` uses it instead of running `Readable` on a thread.""" + + async def get_async(self, path: str, byte_range: ByteRange | None) -> Found | Missing: ... + + async def get_if_changed_async( + self, path: str, generation: Generation, byte_range: ByteRange | None + ) -> Found | Missing | Unchanged: ... + + async def get_ranges_async( + self, path: str, ranges: Sequence[ByteRange] + ) -> FoundRanges | Missing: ... + + async def head_async(self, path: str) -> ObjectMetadata | Missing: ... + + +@runtime_checkable +class ReadableIntoAsync(Backend, Protocol[O_contra]): + """`ReadableInto`, as a coroutine.""" + + async def get_into_async( + self, path: str, out: O_contra, byte_range: ByteRange | None + ) -> Copied | Missing: ... + + +@runtime_checkable +class WritableAsync(Backend, Protocol): + """`Writable`, as coroutines.""" + + async def put_async(self, path: str, value: memoryview) -> Written: ... + + async def put_if_absent_async(self, path: str, value: memoryview) -> Written | Rejected: ... + + async def delete_async(self, path: str) -> Deleted | Missing: ... + + async def delete_dir_async(self, directory: str) -> None: ... + + +@runtime_checkable +class WritableIfMatchAsync(Backend, Protocol): + """`WritableIfMatch`, as a coroutine.""" + + async def put_if_match_async( + self, path: str, value: memoryview, generation: Generation + ) -> Written | Rejected | Missing: ... + + +@runtime_checkable +class DeletableIfMatchAsync(Backend, Protocol): + """`DeletableIfMatch`, as a coroutine.""" + + async def delete_if_match_async( + self, path: str, generation: Generation + ) -> Deleted | Rejected | Missing: ... + + +@runtime_checkable +class ReadableManyAsync(Backend, Protocol): + """`ReadableMany`, as an async iterator.""" + + def get_many_async( + self, requests: Sequence[tuple[str, ByteRange | None]], context: Context + ) -> AsyncIterator[tuple[int, Found | Missing]]: ... + + +@runtime_checkable +class ReadableIntoManyAsync(Backend, Protocol[O_contra]): + """`ReadableIntoMany`, as an async iterator.""" + + def get_into_many_async( + self, requests: Sequence[tuple[str, O_contra, ByteRange | None]], context: Context + ) -> AsyncIterator[tuple[int, Copied | Missing]]: ... + + +@runtime_checkable +class WritableManyAsync(Backend, Protocol): + """`WritableMany`, as async iterators.""" + + def put_many_async( + self, requests: Sequence[tuple[str, memoryview]], context: Context + ) -> AsyncIterator[tuple[int, Written]]: ... + + def delete_many_async( + self, paths: Sequence[str], context: Context + ) -> AsyncIterator[tuple[int, Deleted | Missing]]: ... + + +@runtime_checkable +class ListableAsync(Backend, Protocol): + """`Listable`, as async iterators.""" + + def list_async(self, directory: str) -> AsyncIterator[str]: ... + + def list_dir_async(self, directory: str) -> AsyncIterator[ListItem]: ... diff --git a/packages/zarr-storage/src/zarr_storage/experimental/_resources.py b/packages/zarr-storage/src/zarr_storage/experimental/_resources.py new file mode 100644 index 0000000000..85b010aa9e --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/_resources.py @@ -0,0 +1,538 @@ +"""The resources a store's operations draw on: thread pools, limits on operations in flight, and the +context that holds them. + +Modeled on TensorStore's `Context`: a context maps resource keys to resource objects, a store view +carries one, and every operation through the view takes its resources from it. A backend names the +key its operations are limited under (`Backend.resource_key`) and never holds resources itself. +Resources change how fast operations run, never what they do, so a context is not part of a store's +identity. + +A context left out is `Context.default()`, which resolves every key to a process-wide default, as +TensorStore's thread pools and request limits are shared across independent contexts by default. + +Pickling a resource pickles its settings. Pickle stores each object once, so stores that shared a +resource before pickling share one new resource after; a default unpickles as the receiving +process's default. +""" + +from __future__ import annotations + +import asyncio +import contextvars +import os +import threading +from collections import deque +from concurrent.futures import ThreadPoolExecutor +from functools import partial +from types import MappingProxyType +from typing import TYPE_CHECKING, Final, TypeVar, TypeVarTuple + +if TYPE_CHECKING: + from collections.abc import Callable, Mapping + from concurrent.futures import Future + from types import TracebackType + +__all__ = [ + "Context", + "Limiter", + "Slot", + "ThreadPool", + "default_context", + "default_limiter", + "default_thread_pool", +] + +R = TypeVar("R") +Ts = TypeVarTuple("Ts") + +DEFAULT_THREADS: Final = max(4, os.cpu_count() or 1) +"""Threads in the default pool, as TensorStore's `file_io_concurrency` default.""" + +DEFAULT_LIMIT: Final = 32 +"""Operations in flight under a default limiter, as TensorStore's `s3_request_concurrency`.""" + + +def _check_size(name: str, value: int) -> None: + if type(value) is not int: + raise TypeError(f"{name} must be an int; got {type(value).__name__}.") + if value < 1: + raise ValueError(f"{name} must be >= 1; got {value}.") + + +# ---------------------------------------------------------------------------- thread pools + +_worker = threading.local() +"""Per thread: the `ThreadPool` the thread works for, if any.""" + + +def _mark_worker(pool: ThreadPool) -> None: + _worker.pool = pool + + +class ThreadPool: + """Threads that run blocking operations, such as file I/O. + + The threads start when first needed. Work runs in a copy of the submitter's `contextvars` + context, as `asyncio.to_thread` does. Whoever creates a pool owns it and may `shutdown` it once + nothing needs it; the default pool lives as long as the process. + + Parameters + ---------- + max_workers + The most threads the pool runs at once. + """ + + def __init__(self, max_workers: int) -> None: + _check_size("max_workers", max_workers) + self._max_workers = max_workers + self._lock = threading.Lock() + self._executor: ThreadPoolExecutor | None = None + + @classmethod + def default(cls) -> ThreadPool: + """The process-wide pool, of `DEFAULT_THREADS` threads.""" + return default_thread_pool() + + @property + def max_workers(self) -> int: + return self._max_workers + + def __repr__(self) -> str: + return f"{type(self).__name__}(max_workers={self._max_workers})" + + def __reduce__(self) -> tuple[object, ...]: + return (ThreadPool, (self._max_workers,)) + + def _pool(self) -> ThreadPoolExecutor: + with self._lock: + if self._executor is None: + self._executor = ThreadPoolExecutor( + self._max_workers, + thread_name_prefix="zarr-storage", + initializer=_mark_worker, + initargs=(self,), + ) + return self._executor + + def in_worker(self) -> bool: + """Whether the calling thread is one of this pool's. + + Work started from one of the pool's own threads must not wait for other work queued on the + pool, which may never start; stores run such work inline. + """ + return getattr(_worker, "pool", None) is self + + def submit(self, fn: Callable[[*Ts], R], /, *args: *Ts) -> Future[R]: + """Run `fn(*args)` on one of the pool's threads.""" + context = contextvars.copy_context() + return self._pool().submit(context.run, fn, *args) + + async def run(self, fn: Callable[[*Ts], R], /, *args: *Ts) -> R: + """Await `fn(*args)`, run on one of the pool's threads. + + Called on one of the pool's own threads (an event loop running inside the pool's work), it + runs `fn` inline, since waiting there for work queued on the same pool could wait forever. + Cancelling the awaiting task cancels the work if it hasn't started; work already running + finishes on its thread. + """ + if self.in_worker(): + return fn(*args) + context = contextvars.copy_context() + loop = asyncio.get_running_loop() + return await loop.run_in_executor(self._pool(), partial(context.run, fn, *args)) + + def shutdown(self, *, wait: bool = True) -> None: + """Stop the pool's threads; with `wait`, after the work already given them. + + The pool starts new threads if it is used again. Raises `ValueError` for the default pool, + which other code may be using. + """ + with self._lock: + executor, self._executor = self._executor, None + if executor is not None: + executor.shutdown(wait=wait) + + +class _DefaultThreadPool(ThreadPool): + """The process-wide pool: never shut down, and unpickled as the receiver's own default.""" + + def __reduce__(self) -> tuple[object, ...]: + return (default_thread_pool, ()) + + def shutdown(self, *, wait: bool = True) -> None: + raise ValueError("The default thread pool is shared by the whole process.") + + +_defaults_lock = threading.Lock() +_default_pool: list[ThreadPool] = [] + + +def default_thread_pool() -> ThreadPool: + """The process-wide `ThreadPool`, of `DEFAULT_THREADS` threads.""" + with _defaults_lock: + if not _default_pool: + _default_pool.append(_DefaultThreadPool(DEFAULT_THREADS)) + return _default_pool[0] + + +# ---------------------------------------------------------------------------- limiters + + +class _ThreadWaiter: + """A thread blocked on a limiter.""" + + def __init__(self) -> None: + self._event = threading.Event() + + def grant(self) -> bool: + self._event.set() + return True + + def wait(self) -> None: + self._event.wait() + + +def _resolve(future: asyncio.Future[None]) -> None: + if not future.done(): + future.set_result(None) + + +class _TaskWaiter: + """A task blocked on a limiter, on its own event loop. Fields change under the limiter's lock.""" + + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + self.loop = loop + self.future: asyncio.Future[None] = loop.create_future() + self.granted = False + self.cancelled = False + + def grant(self) -> bool: + if self.cancelled: + return False + try: + self.loop.call_soon_threadsafe(_resolve, self.future) + except RuntimeError: # the loop is closed; nothing waits any more + return False + self.granted = True + return True + + +def _limiter(limit: int, within: Limiter | None) -> Limiter: + return Limiter(limit, within=within) + + +class Limiter: + """A limit on how many operations run at once. + + Threads and tasks on any event loop wait in one first-come, first-served queue. A limiter + `within` another takes a slot of that one too, so a scoped limit can't exceed the limit it + narrows. + + Parameters + ---------- + limit + The most operations that run at once. + within + A limiter whose slots this one's operations also hold. + """ + + def __init__(self, limit: int, *, within: Limiter | None = None) -> None: + _check_size("limit", limit) + self._limit = limit + self._within = within + self._lock = threading.Lock() + self._in_use = 0 + self._waiters: deque[_ThreadWaiter | _TaskWaiter] = deque() + + @property + def limit(self) -> int: + return self._limit + + @property + def within(self) -> Limiter | None: + """The limiter whose slots this one's operations also hold, if any.""" + return self._within + + @property + def in_use(self) -> int: + """How many slots are held now.""" + return self._in_use + + def __repr__(self) -> str: + return f"{type(self).__name__}(limit={self._limit}, in_use={self._in_use})" + + def __reduce__(self) -> tuple[object, ...]: + return (_limiter, (self._limit, self._within)) + + def chain(self) -> tuple[Limiter, ...]: + """This limiter and each it lies within, innermost first.""" + chain: list[Limiter] = [] + current: Limiter | None = self + while current is not None: + chain.append(current) + current = current.within + return tuple(chain) + + def slot(self) -> Slot: + """A context manager, sync (`with`) or async (`async with`), holding a slot of this limiter + and of each limiter it lies within. + + Slots are taken innermost first, so an operation waiting on a narrow limit holds none of the + wider one it narrows. A slot is not re-entrant: code holding one that starts work waiting + for another slot of the same limiter can wait forever, as with a lock. Stores take one slot + per operation; to bound a burst of operations, use a limited view (`Store.limited`). + """ + return Slot(self) + + def _take(self) -> bool: + """Take a free slot if no one is waiting; called under the lock.""" + if self._in_use < self._limit and not self._waiters: + self._in_use += 1 + return True + return False + + def acquire(self) -> None: + """Take a slot of this limiter alone, blocking the calling thread until one is free.""" + with self._lock: + if self._take(): + return + waiter = _ThreadWaiter() + self._waiters.append(waiter) + try: + waiter.wait() + except BaseException: + # Interrupted (KeyboardInterrupt) while waiting: leave the queue, or give back the + # slot if it was granted meanwhile, so the slot isn't lost to a waiter that's gone. + with self._lock: + granted = waiter not in self._waiters + if not granted: + self._waiters.remove(waiter) + if granted: + self.release() + raise + + async def acquire_async(self) -> None: + """Take a slot of this limiter alone, waiting without blocking the event loop.""" + with self._lock: + if self._take(): + return + waiter = _TaskWaiter(asyncio.get_running_loop()) + self._waiters.append(waiter) + try: + await waiter.future + except asyncio.CancelledError: + with self._lock: + granted = waiter.granted + if not granted: + waiter.cancelled = True + self._waiters.remove(waiter) + if granted: + self.release() + raise + + def release(self) -> None: + """Give back a slot of this limiter, to the longest waiter if there is one. + + Raises `RuntimeError` if no slot is held. + """ + with self._lock: + while self._waiters: + if self._waiters.popleft().grant(): + return # the slot passes to the waiter + if self._in_use == 0: + raise RuntimeError("Released a limiter slot that was not held.") + self._in_use -= 1 + + +def _release_all(limiters: list[Limiter]) -> None: + for limiter in reversed(limiters): + limiter.release() + + +class Slot: + """One use of a `Limiter`: holds a slot of it and of each limiter it lies within, innermost + first, from entry to exit.""" + + __slots__ = ("_chain", "_taken") + + def __init__(self, limiter: Limiter) -> None: + self._chain = limiter.chain() + self._taken: list[Limiter] = [] + + def __enter__(self) -> None: + taken: list[Limiter] = [] + try: + for limiter in self._chain: + limiter.acquire() + taken.append(limiter) + except BaseException: + _release_all(taken) + raise + self._taken = taken + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + taken, self._taken = self._taken, [] + _release_all(taken) + + async def __aenter__(self) -> None: + taken: list[Limiter] = [] + try: + for limiter in self._chain: + await limiter.acquire_async() + taken.append(limiter) + except BaseException: + _release_all(taken) + raise + self._taken = taken + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + taken, self._taken = self._taken, [] + _release_all(taken) + + +class _DefaultLimiter(Limiter): + """A process-wide limiter for one key; unpickled as the receiver's limiter for that key.""" + + def __init__(self, key: str) -> None: + super().__init__(DEFAULT_LIMIT) + self._key = key + + def __reduce__(self) -> tuple[object, ...]: + return (default_limiter, (self._key,)) + + +_default_limiters: dict[str, Limiter] = {} + + +def default_limiter(key: str) -> Limiter: + """The process-wide `Limiter` for `key`, of `DEFAULT_LIMIT`.""" + with _defaults_lock: + limiter = _default_limiters.get(key) + if limiter is None: + limiter = _default_limiters[key] = _DefaultLimiter(key) + return limiter + + +# ---------------------------------------------------------------------------- contexts + + +def _context( + threads: ThreadPool | None, limits: Mapping[str, Limiter], parent: Context | None +) -> Context: + return Context(threads=threads, limits=limits, parent=parent) + + +class Context: + """The resources operations draw on: a thread pool, and a limiter per resource key. + + A context is immutable. `child` makes one that overrides some resources and takes the rest from + its parent; a context with no parent takes the rest from the process-wide defaults. Every store + view carries a context (`Store.context`); `with_context` and `limited` return views under + another one. + + Parameters + ---------- + threads + The pool that runs blocking work: a sync backend's operations called through an + `AsyncStore`, and the operations of batches. Left out, the parent's. + limits + A `Limiter` for each resource key it names (a backend's `resource_key`). Keys left out + resolve through the parent. + parent + The context to take unnamed resources from. Left out, the process-wide defaults. + """ + + __slots__ = ("_limits", "_parent", "_threads") + + def __init__( + self, + *, + threads: ThreadPool | None = None, + limits: Mapping[str, Limiter] | None = None, + parent: Context | None = None, + ) -> None: + own = {} if limits is None else dict(limits) + for key, limiter in own.items(): + if not isinstance(limiter, Limiter): # pyright: ignore[reportUnnecessaryIsInstance] + raise TypeError(f"limits[{key!r}] must be a Limiter; got {type(limiter).__name__}.") + if threads is not None and not isinstance(threads, ThreadPool): # pyright: ignore[reportUnnecessaryIsInstance] + raise TypeError(f"threads must be a ThreadPool; got {type(threads).__name__}.") + self._threads = threads + self._limits: Mapping[str, Limiter] = MappingProxyType(own) + self._parent = parent + + @classmethod + def default(cls) -> Context: + """The process-wide context: every key resolves to its process-wide default.""" + return default_context() + + @property + def parent(self) -> Context | None: + return self._parent + + @property + def threads(self) -> ThreadPool: + """The pool that runs blocking work under this context.""" + context: Context | None = self + while context is not None: + if context._threads is not None: + return context._threads + context = context._parent + return default_thread_pool() + + def limiter(self, key: str) -> Limiter: + """The limiter for resource key `key` under this context.""" + context: Context | None = self + while context is not None: + limiter = context._limits.get(key) + if limiter is not None: + return limiter + context = context._parent + return default_limiter(key) + + def child( + self, *, threads: ThreadPool | None = None, limits: Mapping[str, Limiter] | None = None + ) -> Context: + """A context with these resources, taking the rest from this one.""" + return Context(threads=threads, limits=limits, parent=self) + + def limited(self, key: str, limit: int) -> Context: + """A child whose limiter for `key` allows `limit` operations, within this context's.""" + return self.child(limits={key: Limiter(limit, within=self.limiter(key))}) + + def __repr__(self) -> str: + own = ", ".join(f"{key!r}: {limiter!r}" for key, limiter in self._limits.items()) + return f"{type(self).__name__}(threads={self._threads!r}, limits={{{own}}})" + + def __reduce__(self) -> tuple[object, ...]: + return (_context, (self._threads, dict(self._limits), self._parent)) + + +class _DefaultContext(Context): + """The process-wide context; unpickled as the receiver's own.""" + + __slots__ = () + + def __reduce__(self) -> tuple[object, ...]: + return (default_context, ()) + + +_default_context: list[Context] = [] + + +def default_context() -> Context: + """The process-wide `Context`.""" + with _defaults_lock: + if not _default_context: + _default_context.append(_DefaultContext()) + return _default_context[0] diff --git a/packages/zarr-storage/src/zarr_storage/experimental/_store.py b/packages/zarr-storage/src/zarr_storage/experimental/_store.py new file mode 100644 index 0000000000..65d62149e3 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/_store.py @@ -0,0 +1,1021 @@ +"""`Store` and `AsyncStore`: views of a backend at a root, under a context, through sync methods or +coroutines. + +They are where the key grammar, the root, read-only access and the closed check are enforced, +once, for every backend; a backend only sees backend paths. They are also where operations are +scheduled and limited: every operation holds a slot of the view's context's limiter for the +backend's `resource_key`, and blocking work runs on the context's thread pool. + +A slot is taken where the work runs. A sync backend's operation called through an `AsyncStore` +takes its slot on the pool thread that runs it, so no operation ever holds a slot while it waits +for a thread: pool threads waiting for slots and slot holders waiting for threads can't block each +other. An operation whose task is cancelled before it takes its slot is skipped. +""" + +from __future__ import annotations + +import asyncio +import threading +from collections.abc import AsyncGenerator, Generator +from typing import TYPE_CHECKING, Any, Final, Generic, Self, TypeVar, TypeVarTuple, cast, final + +from zarr_storage.experimental._batch import run_many, run_many_async +from zarr_storage.experimental._buffers import byte_view +from zarr_storage.experimental._errors import BatchError, ReadOnlyError, StoreClosedError +from zarr_storage.experimental._keys import check_key, join, normalize_directory, relativize +from zarr_storage.experimental._protocols import ( + Backend, + ClosableAsync, + DeletableIfMatchAsync, + ListableAsync, + ReadableAsync, + ReadableIntoAsync, + ReadableIntoMany, + ReadableIntoManyAsync, + ReadableMany, + ReadableManyAsync, + WritableAsync, + WritableIfMatchAsync, + WritableMany, + WritableManyAsync, +) +from zarr_storage.experimental._resources import default_context +from zarr_storage.experimental._types import Location, Missing + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Buffer, Callable, Iterable, Iterator, Sequence + from types import TracebackType + + from zarr_storage.experimental._protocols import ( + DeletableIfMatch, + Listable, + Readable, + ReadableInto, + Writable, + WritableIfMatch, + ) + from zarr_storage.experimental._resources import Context, Limiter, Slot + from zarr_storage.experimental._types import ( + ByteRange, + Copied, + Deleted, + Found, + FoundRanges, + Generation, + ListItem, + ObjectMetadata, + Rejected, + Unchanged, + Written, + ) + +__all__ = ["AsyncStore", "Store"] + +B_co = TypeVar("B_co", bound=Backend, covariant=True) +O = TypeVar("O") +T = TypeVar("T") +R = TypeVar("R") +Ts = TypeVarTuple("Ts") +Q = TypeVar("Q", bound="str | tuple[str, ByteRange | None]") +"""A `get_many` request: a key, or a key and the part of its value to read.""" + + +class _Abandoned(Exception): + """The operation's awaiting task was cancelled before the operation took its slot.""" + + +def _limited(limiter: Limiter, abandoned: threading.Event, fn: Callable[[*Ts], R], *args: *Ts) -> R: + """`fn(*args)`, holding a slot of `limiter`, on the calling thread; skipped if `abandoned` is + set by the time the slot is free, so a cancelled operation doesn't run long after its caller + moved on.""" + with limiter.slot(): + if abandoned.is_set(): + raise _Abandoned + return fn(*args) + + +def _list_all(fn: Callable[[str], Iterator[T]], directory: str) -> list[T]: + return list(fn(directory)) + + +class _View(Generic[B_co]): + """What `Store` and `AsyncStore` share: a backend, a root, read-only access, a context, and + ownership.""" + + __slots__ = ("_backend", "_context", "_limiter", "_owner", "_read_only", "_root") + + def __init__( + self, + backend: B_co, + *, + read_only: bool, + context: Context | None, + root: str, + owner: bool, + ) -> None: + # Reached only through `Store.__init__`/`AsyncStore.__init__` (an owner at the backend's + # root) and `_derived` (everything else), so ownership is decided once, here. + self._backend: Final[B_co] = backend + self._root: Final[str] = root + self._read_only: Final[bool] = read_only or not backend.writable + self._context: Final[Context] = default_context() if context is None else context + self._limiter: Final[Limiter] = self._context.limiter(backend.resource_key) + self._owner: Final[bool] = owner + + @classmethod + def _derived( + cls, backend: Backend, *, root: str, read_only: bool, context: Context, owner: bool = False + ) -> Self: + """A store of this class over `backend` at a normalized `root`: a view unless `owner`. + + `backend` is the backend of the store it derives from, so of the class's backend type. + """ + store = cls.__new__(cls) + cast("type[_View[Any]]", _View).__init__( + store, + cast("Any", backend), + read_only=read_only, + context=context, + root=root, + owner=owner, + ) + return store + + # ----------------------------------------------------------------- views and identity + + @property + def backend(self) -> B_co: + """The backend this store reads and writes through.""" + return self._backend + + @property + def root(self) -> str: + """This store's directory within the backend; `""` is the backend's root.""" + return self._root + + @property + def read_only(self) -> bool: + """Whether writes through this store are refused.""" + return self._read_only + + @property + def context(self) -> Context: + """The resources this store's operations draw on.""" + return self._context + + @property + def closed(self) -> bool: + """Whether the backend has been closed.""" + return self._backend.closed + + @property + def location(self) -> Location: + """Where this store's keys live: its backend's location, with this store's root.""" + location = self._backend.location + return Location(location.space, join(location.path, self._root)) + + def _view(self, *, root: str, read_only: bool, context: Context) -> Self: + return self._derived(self._backend, root=root, read_only=read_only, context=context) + + def __truediv__(self, directory: str) -> Self: + """A view on the same backend, rooted at `directory` under this store's root.""" + return self._view( + root=join(self._root, normalize_directory(directory)), + read_only=self._read_only, + context=self._context, + ) + + def as_read_only(self) -> Self: + """A view on the same backend, root and context that refuses writes. No view of a + read-only store accepts them.""" + return self._view(root=self._root, read_only=True, context=self._context) + + def with_context(self, context: Context) -> Self: + """A view on the same backend and root whose operations draw on `context`.""" + return self._view(root=self._root, read_only=self._read_only, context=context) + + def limited(self, limit: int) -> Self: + """A view whose operations, together, run at most `limit` at once. + + The limit narrows this view's: an operation holds a slot of both. Batches through the view + start at most `limit` operations at once. + """ + return self.with_context(self._context.limited(self._backend.resource_key, limit)) + + def shares_backend(self, other: Store[Backend] | AsyncStore[Backend]) -> bool: + """Whether `other` reads and writes through the same backend object (and so shares its + state and lifecycle).""" + return self._backend is other._backend + + def overlaps(self, other: Store[Backend] | AsyncStore[Backend]) -> bool: + """Whether a key could be visible through both stores, even over different backend + objects: their `location`s overlap (same space, nested paths).""" + return self.location.overlaps(other.location) + + def __copy__(self) -> Self: + """The store itself: a store is immutable, and a shallow copy would be a second owner of + the same backend object. `copy.deepcopy` copies the backend, and so gives a new owner.""" + return self + + def __repr__(self) -> str: + flags = ", read_only=True" if self._read_only else "" + return f"{type(self).__name__}({self._backend!r}, root={self._root!r}{flags})" + + def __reduce__(self) -> tuple[object, ...]: + return ( + type(self)._restore, + (self._backend, self._root, self._read_only, self._context, self._owner), + ) + + @classmethod + def _restore( + cls, backend: Backend, root: str, read_only: bool, context: Context, owner: bool + ) -> Self: + """A store as pickled: a derived view stays derived, so closing it can't close the backend + it shares with the restored owner.""" + # The backend is the one this class was pickled with; pickle can't carry its type. + return cls._derived(backend, root=root, read_only=read_only, context=context, owner=owner) + + # ----------------------------------------------------------------- path handling + + def _check_open(self) -> None: + if self._backend.closed: + raise StoreClosedError(f"{self!r} is closed.") + + def _path(self, key: str) -> str: + self._check_open() + return join(self._root, check_key(key)) + + def _directory(self, directory: str) -> str: + self._check_open() + return join(self._root, normalize_directory(directory)) + + def _slot(self) -> Slot: + return self._limiter.slot() + + def _refuse_writes(self) -> None: + """Raise `ReadOnlyError` if this store refuses writes. Called after the arguments are + checked, so every write reports a bad argument before the refusal.""" + if self._read_only: + cause = "" if self._backend.writable else ": its backend can't write" + raise ReadOnlyError(f"{self!r} is read-only{cause}.") + + def _writable_path(self, key: str) -> str: + path = self._path(key) + self._refuse_writes() + return path + + def _writable_directory(self, directory: str) -> str: + path = self._directory(directory) + self._refuse_writes() + return path + + def _read_request( + self, request: str | tuple[str, ByteRange | None] + ) -> tuple[str, ByteRange | None]: + if isinstance(request, str): + return self._path(request), None + key, byte_range = request + return self._path(key), byte_range + + def _into_request( + self, request: tuple[str, O] | tuple[str, O, ByteRange | None] + ) -> tuple[str, O, ByteRange | None]: + if len(request) == 2: + key, out = request + return self._path(key), out, None + key, out, byte_range = request + return self._path(key), out, byte_range + + def _writable_paths(self, keys: Sequence[str]) -> list[str]: + """The backend path of each key, refusing a key named twice: its outcome would be a race. + + Checks in the order single writes do: the store is open, the keys, then read-only. + """ + self._check_open() + paths = [self._path(key) for key in keys] + seen: set[str] = set() + for key, path in zip(keys, paths, strict=True): + if path in seen: + raise ValueError(f"The batch names the key {key!r} more than once.") + seen.add(path) + self._refuse_writes() + return paths + + def _put_requests( + self, items: Iterable[tuple[str, Buffer]] + ) -> tuple[list[str], list[tuple[str, memoryview]]]: + batch = list(items) + keys = [key for key, _ in batch] + paths = self._writable_paths(keys) + views = [byte_view(value, writable=False) for _, value in batch] + return keys, list(zip(paths, views, strict=True)) + + +@final +class Store(_View[B_co]): + """A backend seen from a root directory, under a context, through sync methods. + + Construct one store per backend: the store you construct owns the backend and closes it, and it + sees the backend from its root. `store / "a"`, `as_read_only()`, `with_context()`, `limited()` + and `as_async()` return views on the same backend, which share its state and never close it. A + view of a read-only store is read-only too. + + Which methods a store offers depends on its backend's capabilities: a method whose capability + the backend lacks is a type error. `AsyncStore` offers the same operations as coroutines. + + Every operation holds a slot of the context's limiter for the backend's `resource_key`; batches + run their operations on the context's thread pool, at most the limiter's limit at once. + + `backend` gives direct access to the backend, which bypasses the key grammar, the root, the + read-only and closed checks, and the context's limits. So read-only views guard against + mistakes; they are not a security boundary. + + Stores have no value equality: `==` is identity. Use `shares_backend` (the same backend object) + and `overlaps` (keys that could be visible through both, by `location`) to compare stores. + + Parameters + ---------- + backend + The backend to read and write through. + read_only + Refuse writes through this store. A backend that can't write makes every store over it + read-only. + context + The resources operations draw on. Left out, `Context.default()`. + """ + + __slots__ = () + + def __init__( + self, backend: B_co, *, read_only: bool = False, context: Context | None = None + ) -> None: + super().__init__(backend, read_only=read_only, context=context, root="", owner=True) + + def as_async(self) -> AsyncStore[B_co]: + """An `AsyncStore` view on the same backend, root and context; it doesn't own the backend.""" + return AsyncStore[B_co]._derived( + self._backend, root=self._root, read_only=self._read_only, context=self._context + ) + + # ----------------------------------------------------------------- lifecycle + + def close(self) -> None: + """Close the backend, if this store owns it (it was constructed, not derived).""" + if self._owner: + self._backend.close() + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() + + # ----------------------------------------------------------------- batch plumbing + + def _run_many( + self, fn: Callable[[*Ts], R], requests: Sequence[tuple[*Ts]] + ) -> Iterator[tuple[int, R]]: + """`fn` over `requests` on the context's pool, at most the limiter's limit at once.""" + return run_many(fn, requests, self._context.threads, self._limiter.limit) + + def _streamed( + self, batch: Sequence[T], results: Iterator[tuple[int, R]] + ) -> Iterator[tuple[T, R]]: + """`results` paired with their requests; a failure raises `BatchError`.""" + done: set[int] = set() + try: + while True: + # Checked before each result is taken, which may start more reads. + self._check_open() + pair = next(results, None) + if pair is None: + return + index, result = pair + done.add(index) + yield batch[index], result + except ExceptionGroup as group: + raise _batch_error(group, batch, {}, done) from None + finally: + # A caller that stops early must not leave the batch's reads to the garbage collector. + if isinstance(results, Generator): + results.close() + + @staticmethod + def _finished(batch: Sequence[T], results: Iterator[tuple[int, R]]) -> list[tuple[T, R]]: + """Every result, in request order; a failure raises `BatchError` with those that landed.""" + completed: dict[int, R] = {} + try: + completed.update(results) # one pair at a time, so a failure keeps those before it + except ExceptionGroup as group: + raise _batch_error(group, batch, completed, completed.keys()) from None + return [(request, completed[index]) for index, request in enumerate(batch)] + + # ----------------------------------------------------------------- operations on backend paths + + def _get(self: Store[Readable], path: str, byte_range: ByteRange | None) -> Found | Missing: + with self._slot(): + return self._backend.get(path, byte_range) + + def _get_into( + self: Store[ReadableInto[O]], path: str, out: O, byte_range: ByteRange | None + ) -> Copied | Missing: + with self._slot(): + return self._backend.get_into(path, out, byte_range) + + def _put(self: Store[Writable], path: str, value: memoryview) -> Written: + with self._slot(): + return self._backend.put(path, value) + + def _delete(self: Store[Writable], path: str) -> Deleted | Missing: + with self._slot(): + return self._backend.delete(path) + + # ----------------------------------------------------------------- reads + + def get( + self: Store[Readable], key: str, *, byte_range: ByteRange | None = None + ) -> Found | Missing: + """The value at `key`, or the part `byte_range` selects.""" + return self._get(self._path(key), byte_range) + + def get_if_changed( + self: Store[Readable], + key: str, + generation: Generation, + *, + byte_range: ByteRange | None = None, + ) -> Found | Missing | Unchanged: + """`get`, unless the value still has `generation`: then `Unchanged`, and no bytes are read. + + This revalidates a cached copy, as an HTTP `If-None-Match` request does. + """ + path = self._path(key) + with self._slot(): + return self._backend.get_if_changed(path, generation, byte_range) + + def get_ranges( + self: Store[Readable], key: str, ranges: Sequence[ByteRange] + ) -> FoundRanges | Missing: + """Several parts of the value at `key`, all from one generation.""" + path = self._path(key) + with self._slot(): + return self._backend.get_ranges(path, ranges) + + def get_into( + self: Store[ReadableInto[O]], key: str, out: O, *, byte_range: ByteRange | None = None + ) -> Copied | Missing: + """Copy the value at `key` (or part of it) into `out`, a buffer the caller allocated. + + `out` is whatever buffer type the backend reads into: any writable C-contiguous `Buffer` + for the built-in backends, device memory for a GPU direct storage backend. Raises + `ValueError` if `out` is shorter than the bytes to copy or can't be written. + """ + return self._get_into(self._path(key), out, byte_range) + + def head(self: Store[Readable], key: str) -> ObjectMetadata | Missing: + """The size and generation of the value at `key`.""" + path = self._path(key) + with self._slot(): + return self._backend.head(path) + + def exists(self: Store[Readable], key: str) -> bool: + """Whether `key` holds a value.""" + return not isinstance(self.head(key), Missing) + + # ----------------------------------------------------------------- writes + + def put(self: Store[Writable], key: str, value: Buffer) -> Written: + """Write `value` at `key`.""" + return self._put(self._writable_path(key), byte_view(value, writable=False)) + + def put_if_absent(self: Store[Writable], key: str, value: Buffer) -> Written | Rejected: + """Write `value` at `key` if the key holds no value; `Rejected` if it holds one.""" + path = self._writable_path(key) + view = byte_view(value, writable=False) + with self._slot(): + return self._backend.put_if_absent(path, view) + + def put_if_match( + self: Store[WritableIfMatch], key: str, value: Buffer, generation: Generation + ) -> Written | Rejected | Missing: + """Write `value` at `key` if the key's value has `generation`. + + `Rejected` if the key holds another generation, `Missing` if it holds no value. + """ + path = self._writable_path(key) + view = byte_view(value, writable=False) + with self._slot(): + return self._backend.put_if_match(path, view, generation) + + def delete(self: Store[Writable], key: str) -> Deleted | Missing: + """Delete the key `key`. A directory is not a key: deleting one finds it `Missing`.""" + return self._delete(self._writable_path(key)) + + def delete_if_match( + self: Store[DeletableIfMatch], key: str, generation: Generation + ) -> Deleted | Rejected | Missing: + """Delete the key `key` if its value has `generation`.""" + path = self._writable_path(key) + with self._slot(): + return self._backend.delete_if_match(path, generation) + + def delete_dir(self: Store[Writable], directory: str = "") -> None: + """Delete every key under `directory` (by default, every key in this store).""" + path = self._writable_directory(directory) + with self._slot(): + self._backend.delete_dir(path) + + # ----------------------------------------------------------------- batches + + def get_many( + self: Store[Readable], requests: Iterable[Q] + ) -> Iterator[tuple[Q, Found | Missing]]: + """`get` for many keys, yielding `(request, result)` pairs as reads finish. + + A request is a key, or a `(key, byte_range)` pair, and comes back as it was given, so + `dict(store.get_many(keys))` maps keys to results. Keys are checked when `get_many` is + called; the reads run on the context's thread pool as the pairs are taken, at most the + limiter's limit at once, in no particular order. A batch is not atomic: each read is its own + `get`, from whatever generation it finds (`get_ranges` reads several parts of one value from + one generation). + + If reads raise, the iterator yields the reads already running that succeed, then raises + `BatchError` with the requests left in `remaining`; its `completed` is empty, since those + results were yielded. + """ + batch = list(requests) + self._check_open() + paths = [self._read_request(request) for request in batch] + backend = self._backend + if isinstance(backend, ReadableMany): + return self._streamed(batch, backend.get_many(paths, self._context)) + return self._streamed(batch, self._run_many(self._get, paths)) + + def get_into_many( + self: Store[ReadableInto[O]], + requests: Iterable[tuple[str, O] | tuple[str, O, ByteRange | None]], + ) -> Iterator[tuple[tuple[str, O] | tuple[str, O, ByteRange | None], Copied | Missing]]: + """`get_into` for many `(key, out)` or `(key, out, byte_range)` requests, as `get_many`. + + Each request names its own buffer; two requests sharing one write it in no set order. + """ + batch = list(requests) + self._check_open() + paths = [self._into_request(request) for request in batch] + backend = self._backend + if isinstance(backend, ReadableIntoMany): + many = cast("ReadableIntoMany[O]", backend) + return self._streamed(batch, many.get_into_many(paths, self._context)) + return self._streamed(batch, self._run_many(self._get_into, paths)) + + def put_many( + self: Store[Writable], items: Iterable[tuple[str, Buffer]] + ) -> list[tuple[str, Written]]: + """`put` each `(key, value)`, returning `(key, result)` pairs in the order given. + + Every key is checked, and every value viewed, before anything is written; a key named twice + raises `ValueError`. A batch is not atomic. If writes raise, the writes already running + finish, no others start, and `BatchError` reports the keys written (`completed`, with their + results) and the rest (`remaining`). + """ + keys, requests = self._put_requests(items) + backend = self._backend + if isinstance(backend, WritableMany): + return self._finished(keys, backend.put_many(requests, self._context)) + return self._finished(keys, self._run_many(self._put, requests)) + + def delete_many( + self: Store[Writable], keys: Iterable[str] + ) -> list[tuple[str, Deleted | Missing]]: + """`delete` each key, returning `(key, result)` pairs in the order given, as `put_many`.""" + batch = list(keys) + paths = self._writable_paths(batch) + backend = self._backend + if isinstance(backend, WritableMany): + return self._finished(batch, backend.delete_many(paths, self._context)) + return self._finished(batch, self._run_many(self._delete, [(path,) for path in paths])) + + # ----------------------------------------------------------------- listing + + def _open_items(self, items: Iterator[T]) -> Iterator[T]: + """`items`, refusing to continue once the backend closes.""" + for item in items: + self._check_open() + yield item + + def list(self: Store[Listable], directory: str = "") -> Iterator[str]: + """Every key under `directory`, relative to this store's root, in no particular order. + + The directory is checked when `list` is called; iterating after the store closes raises + `StoreClosedError`. Listings hold no slot of the context's limiter. + """ + paths = self._backend.list(self._directory(directory)) + return self._open_items(relativize(path, self._root) for path in paths) + + def list_dir(self: Store[Listable], directory: str = "") -> Iterator[ListItem]: + """The direct children of `directory`, named relative to it. + + A backend may report a `Prefix` that holds no keys, such as an empty directory on a + filesystem. + """ + return self._open_items(self._backend.list_dir(self._directory(directory))) + + +@final +class AsyncStore(_View[B_co]): + """A backend seen from a root directory, under a context, through coroutines. + + The async twin of `Store`: the same operations under the same names, awaited. A backend's async + methods are used where it has them; otherwise its sync methods run on the context's thread + pool, so a backend that only blocks needs no async code. Listings and lazy batches are async + iterators. Construct one per backend, or take `store.as_async()`; `as_sync()` goes back. + Close it with `await store.aclose()` or `async with`. + + Parameters + ---------- + backend + The backend to read and write through. + read_only + Refuse writes through this store. A backend that can't write makes every store over it + read-only. + context + The resources operations draw on. Left out, `Context.default()`. + """ + + __slots__ = () + + def __init__( + self, backend: B_co, *, read_only: bool = False, context: Context | None = None + ) -> None: + super().__init__(backend, read_only=read_only, context=context, root="", owner=True) + + def as_sync(self) -> Store[B_co]: + """A `Store` view on the same backend, root and context; it doesn't own the backend.""" + return Store[B_co]._derived( + self._backend, root=self._root, read_only=self._read_only, context=self._context + ) + + # ----------------------------------------------------------------- lifecycle + + async def aclose(self) -> None: + """Close the backend, if this store owns it (it was constructed, not derived). + + A backend that is `ClosableAsync` is closed with `aclose`; any other with `close`. + """ + if not self._owner: + return + backend = self._backend + if isinstance(backend, ClosableAsync): + await backend.aclose() + else: + backend.close() + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + await self.aclose() + + # ----------------------------------------------------------------- batch plumbing + + async def _in_thread(self, fn: Callable[[*Ts], R], *args: *Ts) -> R: + """`fn(*args)` on the context's pool, holding a slot taken on the pool thread. + + If the cancellation reaches the operation before its slot does, the operation never runs. + On one of the pool's own threads (an event loop running inside the pool's work), the slot + is taken here, without blocking the loop, and `fn` runs inline: blocking the loop's thread + for a slot could wait for a task on that same loop to give one back. + """ + if self._context.threads.in_worker(): + async with self._slot(): + return fn(*args) + abandoned = threading.Event() + try: + return await self._context.threads.run(_limited, self._limiter, abandoned, fn, *args) + except asyncio.CancelledError: + abandoned.set() + raise + + async def _streamed( + self, batch: Sequence[T], results: AsyncIterator[tuple[int, R]] + ) -> AsyncIterator[tuple[T, R]]: + done: set[int] = set() + try: + while True: + self._check_open() + pair = await anext(results, None) + if pair is None: + return + index, result = pair + done.add(index) + yield batch[index], result + except ExceptionGroup as group: + raise _batch_error(group, batch, {}, done) from None + finally: + if isinstance(results, AsyncGenerator): + await results.aclose() + + @staticmethod + async def _finished( + batch: Sequence[T], results: AsyncIterator[tuple[int, R]] + ) -> list[tuple[T, R]]: + completed: dict[int, R] = {} + try: + async for index, result in results: + completed[index] = result # noqa: PERF403 -- a failure keeps those before it + except ExceptionGroup as group: + raise _batch_error(group, batch, completed, completed.keys()) from None + return [(request, completed[index]) for index, request in enumerate(batch)] + + # ----------------------------------------------------------------- operations on backend paths + + async def _get( + self: AsyncStore[ReadableAsync] | AsyncStore[Readable], + path: str, + byte_range: ByteRange | None, + ) -> Found | Missing: + backend = self._backend + if isinstance(backend, ReadableAsync): + async with self._slot(): + return await backend.get_async(path, byte_range) + return await self._in_thread(backend.get, path, byte_range) + + async def _get_into( + self: AsyncStore[ReadableIntoAsync[O]] | AsyncStore[ReadableInto[O]], + path: str, + out: O, + byte_range: ByteRange | None, + ) -> Copied | Missing: + backend = self._backend + if isinstance(backend, ReadableIntoAsync): + async with self._slot(): + return await backend.get_into_async(path, out, byte_range) + return await self._in_thread(backend.get_into, path, out, byte_range) + + async def _put( + self: AsyncStore[WritableAsync] | AsyncStore[Writable], path: str, value: memoryview + ) -> Written: + backend = self._backend + if isinstance(backend, WritableAsync): + async with self._slot(): + return await backend.put_async(path, value) + return await self._in_thread(backend.put, path, value) + + async def _delete( + self: AsyncStore[WritableAsync] | AsyncStore[Writable], path: str + ) -> Deleted | Missing: + backend = self._backend + if isinstance(backend, WritableAsync): + async with self._slot(): + return await backend.delete_async(path) + return await self._in_thread(backend.delete, path) + + # ----------------------------------------------------------------- reads + + async def get( + self: AsyncStore[ReadableAsync] | AsyncStore[Readable], + key: str, + *, + byte_range: ByteRange | None = None, + ) -> Found | Missing: + """As `Store.get`.""" + return await self._get(self._path(key), byte_range) + + async def get_if_changed( + self: AsyncStore[ReadableAsync] | AsyncStore[Readable], + key: str, + generation: Generation, + *, + byte_range: ByteRange | None = None, + ) -> Found | Missing | Unchanged: + """As `Store.get_if_changed`.""" + path = self._path(key) + backend = self._backend + if isinstance(backend, ReadableAsync): + async with self._slot(): + return await backend.get_if_changed_async(path, generation, byte_range) + return await self._in_thread(backend.get_if_changed, path, generation, byte_range) + + async def get_ranges( + self: AsyncStore[ReadableAsync] | AsyncStore[Readable], + key: str, + ranges: Sequence[ByteRange], + ) -> FoundRanges | Missing: + """As `Store.get_ranges`.""" + path = self._path(key) + backend = self._backend + if isinstance(backend, ReadableAsync): + async with self._slot(): + return await backend.get_ranges_async(path, ranges) + return await self._in_thread(backend.get_ranges, path, ranges) + + async def get_into( + self: AsyncStore[ReadableIntoAsync[O]] | AsyncStore[ReadableInto[O]], + key: str, + out: O, + *, + byte_range: ByteRange | None = None, + ) -> Copied | Missing: + """As `Store.get_into`.""" + return await self._get_into(self._path(key), out, byte_range) + + async def head( + self: AsyncStore[ReadableAsync] | AsyncStore[Readable], key: str + ) -> ObjectMetadata | Missing: + """As `Store.head`.""" + path = self._path(key) + backend = self._backend + if isinstance(backend, ReadableAsync): + async with self._slot(): + return await backend.head_async(path) + return await self._in_thread(backend.head, path) + + async def exists(self: AsyncStore[ReadableAsync] | AsyncStore[Readable], key: str) -> bool: + """As `Store.exists`.""" + return not isinstance(await self.head(key), Missing) + + # ----------------------------------------------------------------- writes + + async def put( + self: AsyncStore[WritableAsync] | AsyncStore[Writable], key: str, value: Buffer + ) -> Written: + """As `Store.put`.""" + return await self._put(self._writable_path(key), byte_view(value, writable=False)) + + async def put_if_absent( + self: AsyncStore[WritableAsync] | AsyncStore[Writable], key: str, value: Buffer + ) -> Written | Rejected: + """As `Store.put_if_absent`.""" + path = self._writable_path(key) + view = byte_view(value, writable=False) + backend = self._backend + if isinstance(backend, WritableAsync): + async with self._slot(): + return await backend.put_if_absent_async(path, view) + return await self._in_thread(backend.put_if_absent, path, view) + + async def put_if_match( + self: AsyncStore[WritableIfMatchAsync] | AsyncStore[WritableIfMatch], + key: str, + value: Buffer, + generation: Generation, + ) -> Written | Rejected | Missing: + """As `Store.put_if_match`.""" + path = self._writable_path(key) + view = byte_view(value, writable=False) + backend = self._backend + if isinstance(backend, WritableIfMatchAsync): + async with self._slot(): + return await backend.put_if_match_async(path, view, generation) + return await self._in_thread(backend.put_if_match, path, view, generation) + + async def delete( + self: AsyncStore[WritableAsync] | AsyncStore[Writable], key: str + ) -> Deleted | Missing: + """As `Store.delete`.""" + return await self._delete(self._writable_path(key)) + + async def delete_if_match( + self: AsyncStore[DeletableIfMatchAsync] | AsyncStore[DeletableIfMatch], + key: str, + generation: Generation, + ) -> Deleted | Rejected | Missing: + """As `Store.delete_if_match`.""" + path = self._writable_path(key) + backend = self._backend + if isinstance(backend, DeletableIfMatchAsync): + async with self._slot(): + return await backend.delete_if_match_async(path, generation) + return await self._in_thread(backend.delete_if_match, path, generation) + + async def delete_dir( + self: AsyncStore[WritableAsync] | AsyncStore[Writable], directory: str = "" + ) -> None: + """As `Store.delete_dir`.""" + path = self._writable_directory(directory) + backend = self._backend + if isinstance(backend, WritableAsync): + async with self._slot(): + await backend.delete_dir_async(path) + return + await self._in_thread(backend.delete_dir, path) + + # ----------------------------------------------------------------- batches + + def get_many( + self: AsyncStore[ReadableAsync] | AsyncStore[Readable], requests: Iterable[Q] + ) -> AsyncIterator[tuple[Q, Found | Missing]]: + """As `Store.get_many`; the reads run as tasks, at most the limiter's limit at once.""" + batch = list(requests) + self._check_open() + paths = [self._read_request(request) for request in batch] + backend = self._backend + if isinstance(backend, ReadableManyAsync): + return self._streamed(batch, backend.get_many_async(paths, self._context)) + return self._streamed(batch, run_many_async(self._get, paths, self._limiter.limit)) + + def get_into_many( + self: AsyncStore[ReadableIntoAsync[O]] | AsyncStore[ReadableInto[O]], + requests: Iterable[tuple[str, O] | tuple[str, O, ByteRange | None]], + ) -> AsyncIterator[tuple[tuple[str, O] | tuple[str, O, ByteRange | None], Copied | Missing]]: + """As `Store.get_into_many`.""" + batch = list(requests) + self._check_open() + paths = [self._into_request(request) for request in batch] + backend = self._backend + if isinstance(backend, ReadableIntoManyAsync): + many = cast("ReadableIntoManyAsync[O]", backend) + return self._streamed(batch, many.get_into_many_async(paths, self._context)) + return self._streamed(batch, run_many_async(self._get_into, paths, self._limiter.limit)) + + async def put_many( + self: AsyncStore[WritableAsync] | AsyncStore[Writable], + items: Iterable[tuple[str, Buffer]], + ) -> list[tuple[str, Written]]: + """As `Store.put_many`.""" + keys, requests = self._put_requests(items) + backend = self._backend + if isinstance(backend, WritableManyAsync): + return await self._finished(keys, backend.put_many_async(requests, self._context)) + return await self._finished(keys, run_many_async(self._put, requests, self._limiter.limit)) + + async def delete_many( + self: AsyncStore[WritableAsync] | AsyncStore[Writable], keys: Iterable[str] + ) -> list[tuple[str, Deleted | Missing]]: + """As `Store.delete_many`.""" + batch = list(keys) + paths = self._writable_paths(batch) + backend = self._backend + if isinstance(backend, WritableManyAsync): + return await self._finished(batch, backend.delete_many_async(paths, self._context)) + requests = [(path,) for path in paths] + return await self._finished( + batch, run_many_async(self._delete, requests, self._limiter.limit) + ) + + # ----------------------------------------------------------------- listing + + async def _open_items(self, items: AsyncIterator[T]) -> AsyncIterator[T]: + async for item in items: + self._check_open() + yield item + + async def _listed_in_thread( + self, fn: Callable[[str], Iterator[T]], directory: str + ) -> AsyncIterator[T]: + """A sync listing, taken whole on the context's pool.""" + for item in await self._context.threads.run(_list_all, fn, directory): + yield item + + def list( + self: AsyncStore[ListableAsync] | AsyncStore[Listable], directory: str = "" + ) -> AsyncIterator[str]: + """As `Store.list`.""" + path = self._directory(directory) + backend = self._backend + if isinstance(backend, ListableAsync): + paths = backend.list_async(path) + else: + paths = self._listed_in_thread(backend.list, path) + return self._open_items(_relativized(paths, self._root)) + + def list_dir( + self: AsyncStore[ListableAsync] | AsyncStore[Listable], directory: str = "" + ) -> AsyncIterator[ListItem]: + """As `Store.list_dir`.""" + path = self._directory(directory) + backend = self._backend + if isinstance(backend, ListableAsync): + return self._open_items(backend.list_dir_async(path)) + return self._open_items(self._listed_in_thread(backend.list_dir, path)) + + +def _batch_error( + group: ExceptionGroup[Exception], + batch: Sequence[T], + completed: dict[int, R], + done: Iterable[int], +) -> BatchError: + finished = set(done) + return BatchError( + f"{len(group.exceptions)} of {len(batch)} operations in a batch failed.", + group.exceptions, + completed=tuple((batch[index], result) for index, result in sorted(completed.items())), + remaining=tuple(request for index, request in enumerate(batch) if index not in finished), + ) + + +async def _relativized(paths: AsyncIterator[str], root: str) -> AsyncIterator[str]: + async for path in paths: + yield relativize(path, root) diff --git a/packages/zarr-storage/src/zarr_storage/experimental/_types.py b/packages/zarr-storage/src/zarr_storage/experimental/_types.py new file mode 100644 index 0000000000..2013c7dc42 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/_types.py @@ -0,0 +1,221 @@ +"""Values that stores take and return. All are immutable.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, NewType + +from zarr_storage.experimental._keys import check_key, is_within + +if TYPE_CHECKING: + from collections.abc import Hashable + +__all__ = [ + "ByteRange", + "Copied", + "Deleted", + "Entry", + "Found", + "FoundRanges", + "Generation", + "Key", + "ListItem", + "Location", + "Missing", + "ObjectMetadata", + "OffsetRequest", + "Prefix", + "RangeRequest", + "Rejected", + "SuffixRequest", + "Unchanged", + "Written", +] + +Generation = NewType("Generation", object) +"""An opaque token for the state of one key, compared only by equality. + +Backends mint it: a counter (memory), `(device, inode, mtime_ns, size)` (local files), an ETag +(object stores). Two reads that return equal generations read the same value. +""" + + +@dataclass(frozen=True, slots=True) +class Location: + """Where keys live, so stores over different backend objects can tell whether they see the same + data. + + `space` is everything except the path that decides which data a key names: `("file",)` for the + local filesystem, the bucket for an object store, or an object that only equals itself for data + one backend alone holds. `path` is a directory in that space, `/`-separated, without a leading or + trailing `/`; `""` is the space's root. Credentials are never part of a location. + """ + + space: Hashable + path: str + + def __post_init__(self) -> None: + if self.path != "": + check_key(self.path) # a normalized directory: no leading, trailing or doubled `/` + + def overlaps(self, other: Location) -> bool: + """Whether a key could lie under both: same space, and one path within the other.""" + return self.space == other.space and ( + is_within(self.path, other.path) or is_within(other.path, self.path) + ) + + +def _check_offsets(**offsets: int) -> None: + for name, value in offsets.items(): + if type(value) is not int: + raise TypeError(f"{name} must be an int; got {type(value).__name__}.") + + +@dataclass(frozen=True, slots=True) +class RangeRequest: + """The bytes from `start` (inclusive) to `end` (exclusive).""" + + start: int + end: int + + def __post_init__(self) -> None: + _check_offsets(start=self.start, end=self.end) + if self.start < 0 or self.end < self.start: + raise ValueError( + f"A range needs 0 <= start <= end; got start={self.start}, end={self.end}." + ) + + +@dataclass(frozen=True, slots=True) +class OffsetRequest: + """The bytes from `start` (inclusive) to the end of the value.""" + + start: int + + def __post_init__(self) -> None: + _check_offsets(start=self.start) + if self.start < 0: + raise ValueError(f"An offset must be >= 0; got {self.start}.") + + +@dataclass(frozen=True, slots=True) +class SuffixRequest: + """The last `length` bytes of the value, or the whole value if it is shorter.""" + + length: int + + def __post_init__(self) -> None: + _check_offsets(length=self.length) + if self.length < 0: + raise ValueError(f"A suffix length must be >= 0; got {self.length}.") + + +ByteRange = RangeRequest | OffsetRequest | SuffixRequest +"""A part of a value. An end past the value is clamped; a start past the value is an error.""" + + +@dataclass(frozen=True, slots=True) +class Found: + """A read found the key: its bytes (or the requested part) and their generation.""" + + value: memoryview + generation: Generation + read_at: float | None = None + """When the store read the value, in seconds since the UNIX epoch, if the backend knows.""" + + +@dataclass(frozen=True, slots=True) +class FoundRanges: + """A read found the key: the bytes of several ranges, all from one generation.""" + + values: tuple[memoryview, ...] + generation: Generation + read_at: float | None = None + + +@dataclass(frozen=True, slots=True) +class Copied: + """A read found the key and copied `size` bytes into the caller's buffer.""" + + size: int + generation: Generation + read_at: float | None = None + + +@dataclass(frozen=True, slots=True) +class Missing: + """The key holds no value (an HTTP store's `404`). + + `read_at` records when the store looked, if the backend knows, so an absence can be cached like + a value. + """ + + read_at: float | None = None + + +@dataclass(frozen=True, slots=True) +class Unchanged: + """`get_if_changed` named the key's current generation, so no bytes were read (an HTTP `304`).""" + + generation: Generation + read_at: float | None = None + + +@dataclass(frozen=True, slots=True) +class Written: + """A write stored its value, which has `generation`.""" + + generation: Generation + + +@dataclass(frozen=True, slots=True) +class Deleted: + """A delete removed the key's value, which had `generation`.""" + + generation: Generation + + +@dataclass(frozen=True, slots=True) +class Rejected: + """A conditional write or delete changed nothing: the key holds a value with `generation`. + + `put_if_absent` is rejected by any value; `put_if_match` and `delete_if_match` by a value whose + generation is not the one they named. + """ + + generation: Generation + + +@dataclass(frozen=True, slots=True) +class ObjectMetadata: + """What a store knows about one key without reading its value.""" + + size: int + generation: Generation + last_modified: float | None + """Seconds since the UNIX epoch, or `None` if the backend does not track it.""" + + +@dataclass(frozen=True, slots=True) +class Key: + """A key directly inside the listed directory. `name` has no `/`.""" + + name: str + + +@dataclass(frozen=True, slots=True) +class Prefix: + """A directory directly inside the listed directory. `name` has no `/`.""" + + name: str + + +@dataclass(frozen=True, slots=True) +class Entry: + """A child of the listed directory that the backend can't classify as a key or a directory.""" + + name: str + + +ListItem = Key | Prefix | Entry +"""One child of a listed directory. A name can appear both as a `Key` and as a `Prefix`.""" diff --git a/packages/zarr-storage/src/zarr_storage/experimental/backends/__init__.py b/packages/zarr-storage/src/zarr_storage/experimental/backends/__init__.py new file mode 100644 index 0000000000..c0760a9290 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/backends/__init__.py @@ -0,0 +1,24 @@ +"""Backends: the objects a `Store` reads and writes through. + +`ObjectStoreBackend` needs the `obstore` extra and is imported on first use. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from zarr_storage.experimental.backends._local import LocalBackend +from zarr_storage.experimental.backends._memory import MemoryBackend + +if TYPE_CHECKING: + from zarr_storage.experimental.backends._obstore import ObjectStoreBackend + +__all__ = ["LocalBackend", "MemoryBackend", "ObjectStoreBackend"] + + +def __getattr__(name: str) -> object: + if name == "ObjectStoreBackend": + from zarr_storage.experimental.backends._obstore import ObjectStoreBackend + + return ObjectStoreBackend + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/packages/zarr-storage/src/zarr_storage/experimental/backends/_common.py b/packages/zarr-storage/src/zarr_storage/experimental/backends/_common.py new file mode 100644 index 0000000000..038ae1f5a7 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/backends/_common.py @@ -0,0 +1,99 @@ +"""Helpers shared by backends: preconditions, listing a flat set of keys, and locations. + +A precondition is a function of a key's current generation (`None` if the key is absent) that +returns the outcome that refuses the operation, or `None` to let it proceed. A backend writes each +operation once, parameterized by its precondition; the return type follows from the precondition's, +so `put` (with `always`) returns only `Written`. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from zarr_storage.experimental._keys import is_within, relativize +from zarr_storage.experimental._types import Key, Missing, Prefix, Rejected + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + + from zarr_storage.experimental._types import Generation, ListItem + +__all__ = [ + "LOCAL_FILESYSTEM", + "IfMatch", + "Only", + "always", + "children", + "if_absent", + "strictly_within", +] + +LOCAL_FILESYSTEM = ("file",) +"""The `Location.space` of every backend over this machine's filesystem.""" + + +class Only: + """A `Location.space` that equals only another wrapping the same object: data one backend (or + store) alone holds. It compares by identity even when the object defines its own equality, as + obstore's stores do.""" + + __slots__ = ("_of",) + + def __init__(self, of: object) -> None: + self._of = of + + def __eq__(self, other: object) -> bool: + return isinstance(other, Only) and other._of is self._of + + def __hash__(self) -> int: + return id(self._of) + + def __repr__(self) -> str: + return f"Only({type(self._of).__name__} at {id(self._of):#x})" + + +def always(current: Generation | None) -> None: + """The precondition of an unconditional operation: it always proceeds.""" + + +def if_absent(current: Generation | None) -> Rejected | None: + """Proceed only if the key holds no value.""" + return None if current is None else Rejected(current) + + +@dataclass(frozen=True, slots=True) +class IfMatch: + """Proceed only if the key's value has `generation`.""" + + generation: Generation + + def __call__(self, current: Generation | None) -> Rejected | Missing | None: + if current is None: + return Missing() + if current != self.generation: + return Rejected(current) + return None + + +def strictly_within(path: str, directory: str) -> bool: + """Whether `path` lies under `directory` (normalized) and is not `directory` itself.""" + return path != directory and is_within(path, directory) + + +def children(paths: Iterable[str], directory: str) -> Iterator[ListItem]: + """The direct children of `directory` among a flat set of key paths. + + A path directly inside `directory` is a `Key`; the first segment of a deeper path is a + `Prefix`, reported once. A name can be both. + """ + seen_prefixes: set[str] = set() + for path in paths: + if not strictly_within(path, directory): + continue + name, sep, _ = relativize(path, directory).partition("/") + if not sep: + yield Key(name) + elif name not in seen_prefixes: + seen_prefixes.add(name) + yield Prefix(name) diff --git a/packages/zarr-storage/src/zarr_storage/experimental/backends/_local.py b/packages/zarr-storage/src/zarr_storage/experimental/backends/_local.py new file mode 100644 index 0000000000..4983e1fe46 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/backends/_local.py @@ -0,0 +1,996 @@ +"""A backend over a directory on the local filesystem.""" + +from __future__ import annotations + +import contextlib +import errno +import os +import shutil +import stat +import sys +import threading +import time +import uuid +from pathlib import Path +from typing import TYPE_CHECKING, Self, TypedDict, TypeVar + +from zarr_storage.experimental._buffers import byte_view +from zarr_storage.experimental._byte_range import resolve +from zarr_storage.experimental._errors import ( + InvalidKeyError, + KeyConflictError, + UnsupportedOperationError, +) +from zarr_storage.experimental._keys import check_key +from zarr_storage.experimental._types import ( + Copied, + Deleted, + Found, + FoundRanges, + Generation, + Key, + Location, + Missing, + ObjectMetadata, + Prefix, + Unchanged, + Written, +) +from zarr_storage.experimental.backends._common import LOCAL_FILESYSTEM, IfMatch, always, if_absent + +if TYPE_CHECKING: + from collections.abc import Buffer, Callable, Generator, Iterator, Sequence + from io import BufferedReader + + from zarr_storage.experimental._types import ByteRange, ListItem, Rejected + +__all__ = ["RESERVED_SUFFIX", "LocalBackend", "segment_problem"] + +RESERVED_SUFFIX = ".__zarr_local" +"""File names ending with this suffix belong to the backend: temporary files and lock files. + +Keys with a segment ending in it are refused, and listings skip such names, as TensorStore's file +driver does for its own lock files. +""" + +_LOCK_NAME = f"lock{RESERVED_SUFFIX}" +_STAGING_NAME = f"staging{RESERVED_SUFFIX}" +"""The directory under the root where writes stage values before renaming them into place.""" + +_WRITE_ATTEMPTS = 64 +"""How many times a write starts over after a concurrent `delete_dir` removed its directory.""" + +_WINDOWS = sys.platform == "win32" + +_WINDOWS_DEVICE_NAMES = frozenset( + ["CON", "PRN", "AUX", "NUL"] + + [f"{name}{i}" for name in ("COM", "LPT") for i in [*range(1, 10), "¹", "²", "³"]] +) +_WINDOWS_FORBIDDEN_CHARACTERS = frozenset('<>:"\\|?*') | frozenset(chr(i) for i in range(32)) + +_FD_WALK = ( + os.open in os.supports_dir_fd + and os.unlink in os.supports_dir_fd + and os.rmdir in os.supports_dir_fd + and os.scandir in os.supports_fd + and hasattr(os, "O_NOFOLLOW") + and hasattr(os, "O_DIRECTORY") +) +"""Whether `delete_dir` can walk by file descriptor, so a directory swapped for a symlink while it +walks is never followed (as `shutil.rmtree` does where it can). Not on Windows.""" + +_DIRECTORY_FLAGS = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) +"""Open a directory itself, refusing a symlink in its place.""" + +_NOT_A_DIRECTORY_HERE = (errno.ENOTDIR, errno.ELOOP) +"""What opening a name with `_DIRECTORY_FLAGS` reports when the name is a file or a symlink.""" + +_IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 +"""The reparse tag of a Windows directory junction, which `is_symlink` doesn't report.""" + +R = TypeVar("R") +T = TypeVar("T") + + +class _State(TypedDict): + root: str + closed: bool + + +class _Retry(Exception): + """A concurrent `delete_dir` removed a directory a write was using; start the write over.""" + + +_NONBLOCK = getattr(os, "O_NONBLOCK", 0) + +_TRANSIENT_ERRNOS = (errno.ENOENT, errno.EINVAL) +"""What creating a file in, or renaming into, a directory being removed reports. + +macOS reports EINVAL rather than ENOENT for a file created in a directory being removed. +""" + + +def _generation(st: os.stat_result) -> Generation: + return Generation((st.st_dev, st.st_ino, st.st_mtime_ns, st.st_size)) + + +_stamp_lock = threading.Lock() +_last_stamp = 0 + + +def _unique_stamp() -> int: + """A nanosecond time, at least now, and later than any this process has handed out. + + Every write stamps its file's mtime with one. A filesystem can reuse an inode as soon as a file + is deleted (ext4 does) and only advances mtimes once per clock tick, so without the stamp a + generation `(dev, inode, mtime_ns, size)` could come back for a different value, and a stale + `if_match` would succeed. + """ + global _last_stamp + with _stamp_lock: + _last_stamp = max(time.time_ns(), _last_stamp + 1) + return _last_stamp + + +def _set_mtime(fd: int, path: Path, stamp: int) -> None: + if os.utime in os.supports_fd: + os.utime(fd, ns=(stamp, stamp)) + else: + os.utime(path, ns=(stamp, stamp)) + + +_PROBE_STAMP = 1_700_000_000_123_456_789 +"""An mtime with every digit significant, to see whether a filesystem keeps nanoseconds.""" + + +def segment_problem(segment: str, *, windows: bool) -> str | None: + """Why a filesystem can't hold `segment` as one file or directory name, or `None` if it can. + + On every platform the backend's reserved suffix is refused. With `windows=True`, so are the + names Windows reads as something else: separators, `:` (a drive or stream), other forbidden + characters, device names such as `NUL` or `com1.txt`, and names ending in `.` or a space, which + Windows strips. + """ + if _is_reserved(segment): + return ( + f"names ending in {RESERVED_SUFFIX!r}, in any case, are reserved by the local backend" + ) + if not windows: + return None + if not _WINDOWS_FORBIDDEN_CHARACTERS.isdisjoint(segment): + return 'Windows forbids the characters <>:"|?*\\ and control characters in names' + if segment.split(".")[0].upper() in _WINDOWS_DEVICE_NAMES: + return "Windows reserves device names such as NUL, CON and COM1" + if segment.endswith((".", " ")): + return "Windows strips a trailing '.' or space from names" + return None + + +def _is_reserved(name: str) -> bool: + """Whether `name` is the backend's own, as a filesystem that ignores case would read it.""" + return name.casefold().endswith(RESERVED_SUFFIX) + + +def _check_segments(path: str) -> None: + for segment in path.split("/"): + problem = segment_problem(segment, windows=_WINDOWS) + if problem is not None: + raise InvalidKeyError(f"{path!r} can't be stored on this filesystem: {problem}.") + + +@contextlib.contextmanager +def _key_errors(path: str) -> Generator[None, None, None]: + """Report a name the filesystem can't hold as an invalid key.""" + try: + yield + except OSError as e: + if e.errno == errno.ENAMETOOLONG: + raise InvalidKeyError(f"{path!r} is too long for this filesystem.") from e + raise + + +def _open_key(file: Path) -> BufferedReader | None: + """The file at `file` opened for reading, or `None` if it is absent or is not a regular file. + + Opened without blocking, so a FIFO in a key's place reads as absent instead of waiting for a + writer, as `head` and listings already treat it. + """ + try: + fd = os.open(file, os.O_RDONLY | _NONBLOCK | getattr(os, "O_BINARY", 0)) + except (FileNotFoundError, IsADirectoryError, NotADirectoryError): + return None + except PermissionError: + # Windows refuses to open a directory with PermissionError. + if file.is_dir(): + return None + raise + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + os.close(fd) + return None + if _NONBLOCK: + os.set_blocking(fd, True) + return open(fd, "rb") + except BaseException: + with contextlib.suppress(OSError): + os.close(fd) + raise + + +def _read(f: BufferedReader, st: os.stat_result, byte_range: ByteRange | None) -> Found: + """The part of the open file `f`, whose stat is `st`, that `byte_range` selects.""" + start, end = resolve(byte_range, st.st_size) + f.seek(start) + return Found(memoryview(f.read(end - start)), _generation(st), time.time()) + + +def _read_exact_into(f: BufferedReader, out: memoryview) -> None: + filled = 0 + while filled < len(out): + n = f.readinto(out[filled:]) + if n == 0: + raise OSError("The file shrank while it was being read.") + filled += n + + +def _stat_key(file: Path) -> os.stat_result | None: + """The file's stat, or `None` if it is absent or is not a regular file.""" + try: + st = file.stat() + except (FileNotFoundError, NotADirectoryError): + return None + return st if stat.S_ISREG(st.st_mode) else None + + +@contextlib.contextmanager +def _directory_lock(directory: Path, *, dir_fd: int | None = None) -> Generator[None, None, None]: + """Hold the exclusive lock of one directory. + + Every write and delete of a key holds the lock of the key's directory while it checks + preconditions and renames or unlinks. The lock lives in the directory itself, so two backends + whose roots overlap use the same lock for the same key. `delete_dir` removes a directory only + while holding its lock; a waiter that wakes holding the removed lock file tries again. + + Locks are taken ancestor before descendant, never the other way, so they can't deadlock. + + With `dir_fd`, the directory is the one open as `dir_fd`, and `directory` is ignored. + + Raises `_Retry` if the directory is being removed. + """ + lock_path = directory / _LOCK_NAME if dir_fd is None else _LOCK_NAME + while True: + try: + fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o644, dir_fd=dir_fd) + except NotADirectoryError as e: + # The directory was removed and a key of the same name written in its place. + raise _Retry from e + except OSError as e: + if e.errno in _TRANSIENT_ERRNOS: + raise _Retry from e + raise + try: + _lock(fd) + held = os.fstat(fd) + try: + current = os.stat(lock_path, dir_fd=dir_fd) + except (FileNotFoundError, NotADirectoryError): + current = None + if current is not None and (current.st_dev, current.st_ino) == ( + held.st_dev, + held.st_ino, + ): + break + _unlock(fd) + except BaseException: + os.close(fd) + raise + os.close(fd) + try: + yield + finally: + _unlock(fd) + os.close(fd) + + +def _replace_if( + file: Path, + path: str, + temp: Path, + staged: Generation, + check: Callable[[Generation | None], R | None], +) -> Written | R: + """Rename `temp` to `file` if `check` lets it. The caller holds the directory's lock. + + `staged` is the generation of `temp`; a rename keeps the inode, mtime and size, so it is the + generation of the written key too. A directory in the way is a conflict, whatever the + preconditions, unless it holds no keys; then it gives way. + """ + if _is_real_directory(file) and not _reclaim(file): + raise KeyConflictError(f"{path!r} is a directory, so it can't also be a key.") + st = _stat_key(file) + refusal = check(None if st is None else _generation(st)) + if refusal is not None: + return refusal + try: + os.replace(temp, file) + except (IsADirectoryError, PermissionError) as e: + if _is_real_directory(file): + # Deletes leave directories behind; one that holds no keys gives way to the key. + if not _reclaim(file): + raise KeyConflictError( + f"{path!r} is a directory, so it can't also be a key." + ) from e + raise _Retry from e + if isinstance(e, IsADirectoryError): + raise _Retry from e # The directory in the way vanished meanwhile. + raise + except OSError as e: + if e.errno in _TRANSIENT_ERRNOS: + raise _Retry from e + raise + return Written(staged) + + +def _is_real_directory(path: Path) -> bool: + """Whether `path` is a directory itself, not a symlink to one (a symlink is a key's file).""" + return path.is_dir() and not path.is_symlink() + + +def _reclaim(directory: Path) -> bool: + """Remove `directory` if no key lies under it, and say whether it is gone. + + Only empty directories are removed, with `rmdir`, deepest first, each under its own lock + (ancestor before descendant). A file anywhere stops it, and so does a writer adding one meanwhile: + `rmdir` refuses a directory that isn't empty, so a reclaim can never remove a key. Another + operation can recreate a directory's lock file between its removal and the `rmdir`; then the + directory is scanned again. + """ + for _ in range(_WRITE_ATTEMPTS): + try: + with _directory_lock(directory): + with os.scandir(directory) as entries: + children = [e for e in entries if e.name != _LOCK_NAME] + for entry in children: + if not entry.is_dir(follow_symlinks=False) or entry.name.endswith( + RESERVED_SUFFIX + ): + return False + if not _reclaim(Path(entry.path)): + return False + os.unlink(directory / _LOCK_NAME) + os.rmdir(directory) + except (_Retry, FileNotFoundError): + return True + except OSError as e: + if e.errno == errno.ENOTEMPTY: + continue + raise + return True + return False + + +def _remove_tree_at(fd: int, parent_fd: int | None, name: str) -> None: + """`_remove_tree` of the directory open as `fd`, walking by file descriptor. + + Each subdirectory is opened relative to its parent's descriptor and never through a symlink, so + a directory replaced by a symlink while the walk runs is unlinked as a link, never followed. + With `parent_fd`, the directory, named `name` in the parent, is removed too. + """ + try: + with _directory_lock(Path(), dir_fd=fd): + with os.scandir(fd) as entries: + children = [ + (e.name, e.is_dir(follow_symlinks=False)) + for e in entries + if e.name != _LOCK_NAME + ] + for child, is_directory in children: + if _is_reserved(child): + # Below the root, this is a nested backend's staging directory; at the root, + # it is this backend's own and stays. + if parent_fd is not None: + shutil.rmtree(child, dir_fd=fd, ignore_errors=True) + continue + if is_directory: + _remove_subtree(fd, child) + else: + with contextlib.suppress(FileNotFoundError): + os.unlink(child, dir_fd=fd) + if parent_fd is not None: + os.unlink(_LOCK_NAME, dir_fd=fd) + try: + os.rmdir(name, dir_fd=parent_fd) + except OSError as e: + if e.errno not in (errno.ENOTEMPTY, errno.ENOENT, errno.ENOTDIR): + raise + except (_Retry, FileNotFoundError, NotADirectoryError): + return # The directory is already gone. + + +def _remove_subtree(parent_fd: int, name: str) -> None: + """Remove the directory `name` in the directory open as `parent_fd`, by descriptor.""" + try: + fd = os.open(name, _DIRECTORY_FLAGS, dir_fd=parent_fd) + except FileNotFoundError: + return + except OSError as e: + if e.errno not in _NOT_A_DIRECTORY_HERE: + raise + # Replaced by a key or a symlink since the scan: remove the name, never what it points at. + with contextlib.suppress(FileNotFoundError, IsADirectoryError, PermissionError): + os.unlink(name, dir_fd=parent_fd) + return + try: + _remove_tree_at(fd, parent_fd, name) + finally: + os.close(fd) + + +def _remove_tree(directory: Path, *, remove_self: bool) -> None: + """Delete every key under `directory`, and its subdirectories, each under its own lock. + + Walks by path, for platforms without `dir_fd` (Windows); `_remove_tree_at` is used elsewhere. + + The directory's lock is held while its children are removed, and a child's lock is taken while + the parent's is held (ancestor before descendant), so a writer holding a directory's lock always + finishes before the directory goes. With `remove_self`, `directory` is removed too, unless a + concurrent writer has added to it meanwhile; directories aren't keys, so that is not an error. + """ + try: + with _directory_lock(directory): + with os.scandir(directory) as entries: + children = [e for e in entries if e.name != _LOCK_NAME] + for entry in children: + if _is_reserved(entry.name): + # Below the root, this is a nested backend's staging directory; at the root, + # it is this backend's own and stays. + if remove_self: + shutil.rmtree(entry.path, ignore_errors=True) + continue + if _is_link_entry(entry): + if not entry.is_dir(follow_symlinks=False): + with contextlib.suppress(FileNotFoundError): + os.unlink(entry.path) # the link, never what it points at + continue # a junction: left alone + if entry.is_dir(follow_symlinks=False): + _remove_tree(Path(entry.path), remove_self=True) + else: + with contextlib.suppress(FileNotFoundError): + os.unlink(entry.path) + if remove_self: + os.unlink(directory / _LOCK_NAME) + try: + os.rmdir(directory) + except OSError as e: + if e.errno != errno.ENOTEMPTY: + raise + except (_Retry, FileNotFoundError, NotADirectoryError): + return # The directory is already gone. + + +class LocalBackend: + """Keys stored as files under a root directory. + + A write goes to a temporary file in a staging directory under the root and is renamed into + place, so readers see the old value or the new one, never part of either. The root must not + span filesystems (no mount points under it), since a rename can't cross one. Writes are not + synced to disk. + + Writes and deletes hold the lock of the key's directory while they check preconditions and + rename, which makes conditional writes atomic across threads, processes and backends whose + roots overlap, on one machine. + + Deleting a key leaves its directory in place, so `list_dir` can report a `Prefix` that holds no + keys; a later write of a key with that directory's name removes it if no key lies under it. `delete_dir` removes the + tree bottom-up, taking each directory's lock first, so a write in progress finishes before its + directory goes; it is not atomic, and a key written while it runs may survive it. A write whose + directory a concurrent `delete_dir` removes starts over, with a short backoff, up to 64 times. + + Temporary files and lock files end in `RESERVED_SUFFIX` and are never listed. A crash can leave + staged files behind in the staging directory; they are never read. + + Key names follow the filesystem: on case-insensitive filesystems (the defaults on macOS and + Windows), keys that differ only in case are the same key, and on macOS so are keys that differ + only in Unicode normalization. + + Constructing one reads the filesystem but changes nothing: `root` must already be a directory. + `LocalBackend.create` makes it first. + + Parameters + ---------- + root + The directory that holds the keys. + + Raises + ------ + FileNotFoundError + If `root` doesn't exist. + NotADirectoryError + If `root` is a file. + """ + + def __init__(self, root: str | os.PathLike[str]) -> None: + self._root = Path(root).resolve() + if not self._root.is_dir(): + if self._root.exists(): + raise NotADirectoryError( + f"The root {str(self._root)!r} is a file, not a directory." + ) + raise FileNotFoundError( + f"The root directory {str(self._root)!r} does not exist; " + "`LocalBackend.create` makes it." + ) + self._probe_lock = threading.Lock() + self._exact_times: bool | None = None + self._closed = False + + @classmethod + def create(cls, root: str | os.PathLike[str]) -> Self: + """A backend over `root`, making the directory, and any missing parents, if it doesn't + exist. A root that already exists is used as it is. + + Raises `NotADirectoryError` if `root`, or a parent of it, is a file. + """ + path = Path(root).absolute() # once, so a change of working directory can't move it + try: + path.mkdir(parents=True, exist_ok=True) + except FileExistsError: + raise NotADirectoryError( + f"The root {str(path)!r} can't be made a directory: it, or a directory above it, is " + "a file or a dangling symlink." + ) from None + return cls(path) + + @property + def root(self) -> Path: + """The directory that holds the keys.""" + return self._root + + def __repr__(self) -> str: + return f"LocalBackend({str(self._root)!r})" + + def __getstate__(self) -> _State: + return {"root": str(self._root), "closed": self._closed} + + def __setstate__(self, state: _State) -> None: + self._root = Path(state["root"]) + self._probe_lock = threading.Lock() + self._exact_times = None + self._closed = state["closed"] + + # --- Backend + + @property + def resource_key(self) -> str: + return "local" + + @property + def location(self) -> Location: + """The root on the local filesystem, shared with every other local backend (and obstore's + `LocalStore`) so that nested or equal roots overlap.""" + return Location(LOCAL_FILESYSTEM, self._root.as_posix().strip("/")) + + @property + def closed(self) -> bool: + return self._closed + + @property + def writable(self) -> bool: + return True + + def close(self) -> None: + """Refuse further operations; operations already running finish.""" + self._closed = True + + # --- paths + + def _file(self, path: str) -> Path: + # Backend paths follow the key grammar (`Store` joins its root to a checked key); checked + # again here because the backend is public, and an absolute path or `..` would leave the + # root. + check_key(path) + _check_segments(path) + return self._root / path + + def _directory(self, directory: str) -> Path: + if directory == "": + return self._root + check_key(directory) + _check_segments(directory) + return self._root / directory + + # --- Readable + + def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + with _key_errors(path): + f = _open_key(self._file(path)) + if f is None: + return Missing(time.time()) + with f: + return _read(f, os.fstat(f.fileno()), byte_range) + + def get_if_changed( + self, path: str, generation: Generation, byte_range: ByteRange | None + ) -> Found | Missing | Unchanged: + with _key_errors(path): + f = _open_key(self._file(path)) + if f is None: + return Missing(time.time()) + with f: + st = os.fstat(f.fileno()) + if _generation(st) == generation: + return Unchanged(generation, time.time()) + return _read(f, st, byte_range) + + def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> FoundRanges | Missing: + with _key_errors(path): + f = _open_key(self._file(path)) + if f is None: + return Missing(time.time()) + parts: list[memoryview] = [] + with f: + st = os.fstat(f.fileno()) + for byte_range in ranges: + start, end = resolve(byte_range, st.st_size) + f.seek(start) + parts.append(memoryview(f.read(end - start))) + return FoundRanges(tuple(parts), _generation(st), time.time()) + + def get_into(self, path: str, out: Buffer, byte_range: ByteRange | None) -> Copied | Missing: + view = byte_view(out, writable=True) + with _key_errors(path): + f = _open_key(self._file(path)) + if f is None: + return Missing(time.time()) + with f: + st = os.fstat(f.fileno()) + start, end = resolve(byte_range, st.st_size) + n = end - start + if n > len(view): + raise ValueError(f"The output buffer holds {len(view)} bytes; the value has {n}.") + f.seek(start) + _read_exact_into(f, view[:n]) + return Copied(n, _generation(st), time.time()) + + def head(self, path: str) -> ObjectMetadata | Missing: + with _key_errors(path): + st = _stat_key(self._file(path)) + if st is None: + return Missing(time.time()) + return ObjectMetadata(st.st_size, _generation(st), st.st_mtime) + + # --- Writable + + def put(self, path: str, value: memoryview) -> Written: + return self._put(path, value, always) + + def put_if_absent(self, path: str, value: memoryview) -> Written | Rejected: + return self._put(path, value, if_absent) + + def put_if_match( + self, path: str, value: memoryview, generation: Generation + ) -> Written | Rejected | Missing: + self._require_exact_times() + return self._put(path, value, IfMatch(generation)) + + def _put( + self, path: str, value: memoryview, check: Callable[[Generation | None], R | None] + ) -> Written | R: + file = self._file(path) + last = _Retry() + with _key_errors(path): + for attempt in range(_WRITE_ATTEMPTS): + temp: Path | None = None + try: + temp, staged = self._stage(value) + return self._commit(file, path, temp, staged, check) + except _Retry as retry: + last = retry + time.sleep(min(1e-4 * 2**attempt, 1e-2)) + finally: + if temp is not None: + with contextlib.suppress(OSError): + temp.unlink(missing_ok=True) + raise OSError( + f"Gave up writing {path!r}: a concurrent delete kept removing its directory." + ) from last.__cause__ + + def _require_exact_times(self) -> None: + """Refuse conditional writes on a filesystem that rounds file times. + + Generations need the nanosecond stamps writes set; a filesystem that rounds them (FAT, + HFS+, some network filesystems) could hand an old generation out again. + """ + with self._probe_lock: + if self._exact_times is None: + self._exact_times = self._probe_exact_times() + if not self._exact_times: + raise UnsupportedOperationError( + f"The filesystem under {str(self._root)!r} rounds file times, so generations " + "aren't unique enough for conditional writes." + ) + + def _probe_exact_times(self) -> bool: + staging = self._root / _STAGING_NAME + staging.mkdir(parents=True, exist_ok=True) + probe = staging / f"probe-{uuid.uuid4().hex}" + try: + with open(probe, "xb") as f: + _set_mtime(f.fileno(), probe, _PROBE_STAMP) + return os.fstat(f.fileno()).st_mtime_ns == _PROBE_STAMP + finally: + probe.unlink(missing_ok=True) + + def _stage(self, value: memoryview) -> tuple[Path, Generation]: + """Write `value` to a new file in the staging directory, outside every key's directory. + + Raises `_Retry` if a concurrent delete removed the root or the staging directory. + """ + staging = self._root / _STAGING_NAME + temp = staging / uuid.uuid4().hex + try: + staging.mkdir(parents=True, exist_ok=True) + with open(temp, "xb") as f: + try: + f.write(value) + f.flush() + _set_mtime(f.fileno(), temp, _unique_stamp()) + staged = _generation(os.fstat(f.fileno())) + except BaseException: + # A full disk or an interrupt: the partial file would stay forever. + f.close() + with contextlib.suppress(OSError): + temp.unlink() + raise + except (FileExistsError, NotADirectoryError) as e: + if self._root.exists() and not self._root.is_dir(): + raise KeyConflictError( + f"The root {str(self._root)!r} is now a file (a key of an enclosing store)." + ) from e + # `mkdir` saw the directory, then a concurrent delete removed it. + raise _Retry from e + except OSError as e: + if e.errno in _TRANSIENT_ERRNOS: + raise _Retry from e + raise + return temp, staged + + def _has_key_parent(self, file: Path) -> bool: + """Whether a name between the root and `file` is something no write can turn into a + directory: a key, a special file, or a dangling symlink.""" + parent = file.parent + while parent != self._root: + try: + st = os.stat(parent) # one stat: a concurrent delete_dir can't split the answer + except FileNotFoundError: + if _is_link(parent): + return True # a dangling symlink + except NotADirectoryError: + pass # a name above it is not a directory; checked next + except OSError as e: + if e.errno == errno.ELOOP: + return True # a symlink loop, which no write can turn into a directory + raise + else: + if not stat.S_ISDIR(st.st_mode): + return True + parent = parent.parent + return False + + def _commit( + self, + file: Path, + path: str, + temp: Path, + staged: Generation, + check: Callable[[Generation | None], R | None], + ) -> Written | R: + """Rename `temp` to `file` if `check` lets it, under the lock of `file`'s directory. + + Raises `_Retry` if a concurrent `delete_dir` removed the directory on the way. + """ + try: + file.parent.mkdir(parents=True, exist_ok=True) + except (FileExistsError, NotADirectoryError) as e: + if self._has_key_parent(file): + raise KeyConflictError( + f"A parent of {path!r} is a key (or a special file or dangling symlink), so it " + "can't also be a directory." + ) from e + # `mkdir` saw the directory, then a concurrent delete removed it before `mkdir` checked + # that it was one. + raise _Retry from e + except OSError as e: + if e.errno in _TRANSIENT_ERRNOS: + raise _Retry from e + raise + with _directory_lock(file.parent): + return _replace_if(file, path, temp, staged, check) + + def delete(self, path: str) -> Deleted | Missing: + return self._delete(path, always) + + def delete_if_match(self, path: str, generation: Generation) -> Deleted | Rejected | Missing: + self._require_exact_times() + return self._delete(path, IfMatch(generation)) + + def _delete( + self, path: str, check: Callable[[Generation | None], R | None] + ) -> Deleted | Missing | R: + file = self._file(path) + with _key_errors(path): + try: + with _directory_lock(file.parent): + st = _stat_key(file) + if st is None: + return Missing(time.time()) + current = _generation(st) + refusal = check(current) + if refusal is not None: + return refusal + file.unlink() + except (_Retry, NotADirectoryError): + # The key's directory doesn't exist, or a parent is a key: the key is absent. + return Missing(time.time()) + return Deleted(current) + + def delete_dir(self, directory: str) -> None: + target = self._directory(directory) + with _key_errors(directory): + if _FD_WALK: + self._delete_dir_by_fd(directory) + elif target == self._root: + _remove_tree(self._root, remove_self=False) + elif not self._through_symlink(target) and target.is_dir(): + _remove_tree(target, remove_self=True) + + def _delete_dir_by_fd(self, directory: str) -> None: + """`delete_dir`, opening each directory from the root down relative to its parent and never + through a symlink, so no swap of a directory for a symlink can lead it outside the root.""" + try: + fd = os.open(self._root, os.O_RDONLY | os.O_DIRECTORY) + except (FileNotFoundError, NotADirectoryError): + return + parent: int | None = None + try: + for segment in directory.split("/") if directory else []: + try: + child = os.open(segment, _DIRECTORY_FLAGS, dir_fd=fd) + except FileNotFoundError: + return + except OSError as e: + if e.errno in _NOT_A_DIRECTORY_HERE: + return # a key or a symlink: no directory to delete + raise + if parent is not None: + os.close(parent) + parent, fd = fd, child + _remove_tree_at(fd, parent, directory.rsplit("/", 1)[-1]) + finally: + os.close(fd) + if parent is not None: + os.close(parent) + + def _through_symlink(self, target: Path) -> bool: + """Whether `target`, or a directory between the root and it, is a symlink. + + The tree that listings and `delete_dir` walk stops at a symlink to a directory: what lies + beyond one may lie outside the root, and deleting it could delete data no key names. + """ + while target != self._root and target != target.parent: + if _is_link(target): + return True + target = target.parent + return False + + # --- Listable + + def list(self, directory: str) -> Iterator[str]: + target = self._directory(directory) + prefix = "" if directory == "" else f"{directory}/" + with _key_errors(directory): + if self._through_symlink(target): + return iter(()) + return iter(list(_walk(target, prefix))) + + def list_dir(self, directory: str) -> Iterator[ListItem]: + target = self._directory(directory) + with _key_errors(directory): + if self._through_symlink(target): + return iter(()) + try: + entries = list(os.scandir(target)) + except (FileNotFoundError, NotADirectoryError): + return iter(()) + return _classify(entries) + + +def _walk(directory: Path, prefix: str) -> Iterator[str]: + try: + entries = list(os.scandir(directory)) + except (FileNotFoundError, NotADirectoryError): + return + for entry in entries: + if _is_reserved(entry.name) or _is_junction_entry(entry): + continue + if entry.is_dir(follow_symlinks=False): + yield from _walk(Path(entry.path), f"{prefix}{entry.name}/") + elif _is_key_file(entry): + yield f"{prefix}{entry.name}" + + +def _classify(entries: list[os.DirEntry[str]]) -> Iterator[ListItem]: + for entry in entries: + if _is_reserved(entry.name) or _is_junction_entry(entry): + continue + if entry.is_dir(follow_symlinks=False): + yield Prefix(entry.name) + elif _is_key_file(entry): + yield Key(entry.name) + + +def _is_link(path: Path) -> bool: + """Whether `path` is a symlink, or a Windows directory junction.""" + try: + st = path.lstat() + except (FileNotFoundError, NotADirectoryError): + return False + return stat.S_ISLNK(st.st_mode) or _reparse_tag(st) == _IO_REPARSE_TAG_MOUNT_POINT + + +def _is_junction_entry(entry: os.DirEntry[str]) -> bool: + """Whether `entry` is a Windows directory junction, which `is_dir(follow_symlinks=False)` + reports as a directory. Never on other platforms, where checking would cost a `stat`.""" + if not _WINDOWS: + return False + try: + return _reparse_tag(entry.stat(follow_symlinks=False)) == _IO_REPARSE_TAG_MOUNT_POINT + except OSError: + return False + + +def _is_link_entry(entry: os.DirEntry[str]) -> bool: + return entry.is_symlink() or _is_junction_entry(entry) + + +def _reparse_tag(st: os.stat_result) -> int: + tag: int = getattr(st, "st_reparse_tag", 0) + return tag + + +def _is_key_file(entry: os.DirEntry[str]) -> bool: + """Whether `entry` reads as a key: a regular file, or a symlink to one (as `get` reads it). + + A symlink to a directory, a dangling symlink, and special files are neither keys nor + directories, so listings leave them out. + """ + try: + return entry.is_file() + except OSError: + return False + + +if sys.platform == "win32": + import msvcrt + + def _lock(fd: int) -> None: + os.lseek(fd, 0, os.SEEK_SET) + while True: + try: + msvcrt.locking(fd, msvcrt.LK_LOCK, 1) + except OSError: + continue + return + + def _unlock(fd: int) -> None: + os.lseek(fd, 0, os.SEEK_SET) + msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) + +else: + import fcntl + + def _lock(fd: int) -> None: + fcntl.flock(fd, fcntl.LOCK_EX) + + def _unlock(fd: int) -> None: + fcntl.flock(fd, fcntl.LOCK_UN) diff --git a/packages/zarr-storage/src/zarr_storage/experimental/backends/_memory.py b/packages/zarr-storage/src/zarr_storage/experimental/backends/_memory.py new file mode 100644 index 0000000000..0b38af7a18 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/backends/_memory.py @@ -0,0 +1,266 @@ +"""An in-process backend over a dict.""" + +from __future__ import annotations + +import threading +import time +from dataclasses import dataclass +from typing import TYPE_CHECKING, TypedDict, TypeVar + +from zarr_storage.experimental._buffers import byte_view +from zarr_storage.experimental._byte_range import resolve +from zarr_storage.experimental._types import ( + Copied, + Deleted, + Found, + FoundRanges, + Generation, + Location, + Missing, + ObjectMetadata, + Unchanged, + Written, +) +from zarr_storage.experimental.backends._common import ( + IfMatch, + Only, + always, + children, + if_absent, + strictly_within, +) + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Buffer, Callable, Iterator, Sequence + + from zarr_storage.experimental._types import ByteRange, ListItem, Rejected + +__all__ = ["MemoryBackend"] + +R = TypeVar("R") + + +@dataclass(frozen=True, slots=True) +class _Value: + data: bytes + generation: int + last_modified: float + + +class _State(TypedDict): + values: dict[str, _Value] + next_generation: int + closed: bool + + +class MemoryBackend: + """Values held in a dict in this process. + + Thread-safe. Generations are a counter that increases with every write. A pickled + `MemoryBackend` carries a copy of its values; the copy and the original are independent. + """ + + def __init__(self) -> None: + self._values: dict[str, _Value] = {} + self._next_generation = 1 + self._lock = threading.Lock() + self._closed = False + + def __repr__(self) -> str: + return f"MemoryBackend(<{len(self._values)} keys>)" + + def __getstate__(self) -> _State: + with self._lock: + return { + "values": dict(self._values), + "next_generation": self._next_generation, + "closed": self._closed, + } + + def __setstate__(self, state: _State) -> None: + self._values = state["values"] + self._next_generation = state["next_generation"] + self._lock = threading.Lock() + self._closed = state["closed"] + + # --- Backend + + @property + def resource_key(self) -> str: + return "memory" + + @property + def location(self) -> Location: + """A space of its own: no other backend sees this backend's keys.""" + return Location(Only(self), "") + + @property + def closed(self) -> bool: + return self._closed + + @property + def writable(self) -> bool: + return True + + def close(self) -> None: + self._closed = True + + # --- Readable + + def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + value = self._values.get(path) + if value is None: + return Missing(time.time()) + start, end = resolve(byte_range, len(value.data)) + return Found(memoryview(value.data)[start:end], Generation(value.generation), time.time()) + + def get_if_changed( + self, path: str, generation: Generation, byte_range: ByteRange | None + ) -> Found | Missing | Unchanged: + value = self._values.get(path) + if value is not None and Generation(value.generation) == generation: + return Unchanged(generation, time.time()) + return self.get(path, byte_range) + + def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> FoundRanges | Missing: + value = self._values.get(path) + if value is None: + return Missing(time.time()) + view = memoryview(value.data) + parts = tuple(view[slice(*resolve(r, len(value.data)))] for r in ranges) + return FoundRanges(parts, Generation(value.generation), time.time()) + + def head(self, path: str) -> ObjectMetadata | Missing: + value = self._values.get(path) + if value is None: + return Missing(time.time()) + return ObjectMetadata(len(value.data), Generation(value.generation), value.last_modified) + + def get_into(self, path: str, out: Buffer, byte_range: ByteRange | None) -> Copied | Missing: + view = byte_view(out, writable=True) + value = self._values.get(path) + if value is None: + return Missing(time.time()) + start, end = resolve(byte_range, len(value.data)) + n = end - start + if n > len(view): + raise ValueError(f"The output buffer holds {len(view)} bytes; the value has {n}.") + view[:n] = memoryview(value.data)[start:end] + return Copied(n, Generation(value.generation), time.time()) + + # --- Writable + + def _put( + self, path: str, value: memoryview, check: Callable[[Generation | None], R | None] + ) -> Written | R: + data = bytes(value) + with self._lock: + current = self._values.get(path) + refusal = check(None if current is None else Generation(current.generation)) + if refusal is not None: + return refusal + generation = self._next_generation + self._next_generation += 1 + self._values[path] = _Value(data, generation, time.time()) + return Written(Generation(generation)) + + def put(self, path: str, value: memoryview) -> Written: + return self._put(path, value, always) + + def put_if_absent(self, path: str, value: memoryview) -> Written | Rejected: + return self._put(path, value, if_absent) + + def put_if_match( + self, path: str, value: memoryview, generation: Generation + ) -> Written | Rejected | Missing: + return self._put(path, value, IfMatch(generation)) + + def _delete( + self, path: str, check: Callable[[Generation | None], R | None] + ) -> Deleted | Missing | R: + with self._lock: + current = self._values.get(path) + if current is None: + return Missing(time.time()) + generation = Generation(current.generation) + refusal = check(generation) + if refusal is not None: + return refusal + del self._values[path] + return Deleted(generation) + + def delete(self, path: str) -> Deleted | Missing: + return self._delete(path, always) + + def delete_if_match(self, path: str, generation: Generation) -> Deleted | Rejected | Missing: + return self._delete(path, IfMatch(generation)) + + def delete_dir(self, directory: str) -> None: + with self._lock: + for path in [p for p in self._values if strictly_within(p, directory)]: + del self._values[path] + + # --- Listable + + def list(self, directory: str) -> Iterator[str]: + with self._lock: + paths = list(self._values) + return (p for p in paths if strictly_within(p, directory)) + + def list_dir(self, directory: str) -> Iterator[ListItem]: + with self._lock: + paths = list(self._values) + return children(paths, directory) + + # --- async twins: memory never blocks, so they run inline + + async def get_async(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + return self.get(path, byte_range) + + async def get_if_changed_async( + self, path: str, generation: Generation, byte_range: ByteRange | None + ) -> Found | Missing | Unchanged: + return self.get_if_changed(path, generation, byte_range) + + async def get_ranges_async( + self, path: str, ranges: Sequence[ByteRange] + ) -> FoundRanges | Missing: + return self.get_ranges(path, ranges) + + async def head_async(self, path: str) -> ObjectMetadata | Missing: + return self.head(path) + + async def get_into_async( + self, path: str, out: Buffer, byte_range: ByteRange | None + ) -> Copied | Missing: + return self.get_into(path, out, byte_range) + + async def put_async(self, path: str, value: memoryview) -> Written: + return self.put(path, value) + + async def put_if_absent_async(self, path: str, value: memoryview) -> Written | Rejected: + return self.put_if_absent(path, value) + + async def put_if_match_async( + self, path: str, value: memoryview, generation: Generation + ) -> Written | Rejected | Missing: + return self.put_if_match(path, value, generation) + + async def delete_async(self, path: str) -> Deleted | Missing: + return self.delete(path) + + async def delete_if_match_async( + self, path: str, generation: Generation + ) -> Deleted | Rejected | Missing: + return self.delete_if_match(path, generation) + + async def delete_dir_async(self, directory: str) -> None: + self.delete_dir(directory) + + async def list_async(self, directory: str) -> AsyncIterator[str]: + for path in self.list(directory): + yield path + + async def list_dir_async(self, directory: str) -> AsyncIterator[ListItem]: + for item in self.list_dir(directory): + yield item diff --git a/packages/zarr-storage/src/zarr_storage/experimental/backends/_obstore.py b/packages/zarr-storage/src/zarr_storage/experimental/backends/_obstore.py new file mode 100644 index 0000000000..a5b7e8b6c6 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/backends/_obstore.py @@ -0,0 +1,951 @@ +"""A backend over an obstore store (S3, GCS, Azure, HTTP, local, memory). + +Each operation is written once as plain logic around obstore calls; the sync method and its async +twin differ only in which obstore function they await. The decisions (which put mode, whether an +error means "absent", whether a read is consistent) live in module functions both share. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import errno +import os +import time +from pathlib import Path +from typing import TYPE_CHECKING, TypeVar, cast +from urllib.parse import unquote, urlsplit + +import obstore +from obstore.exceptions import ( + AlreadyExistsError, + GenericError, + NotModifiedError, + PreconditionError, +) +from obstore.store import AzureStore, GCSStore, HTTPStore, LocalStore, S3Store + +from zarr_storage.experimental._buffers import byte_view, copy_into +from zarr_storage.experimental._byte_range import resolve +from zarr_storage.experimental._errors import ( + InvalidKeyError, + KeyConflictError, + UnsupportedOperationError, +) +from zarr_storage.experimental._keys import check_key, relativize +from zarr_storage.experimental._types import ( + Deleted, + Found, + FoundRanges, + Generation, + Key, + Location, + Missing, + ObjectMetadata, + OffsetRequest, + Prefix, + RangeRequest, + Rejected, + SuffixRequest, + Unchanged, + Written, +) +from zarr_storage.experimental.backends._common import ( + LOCAL_FILESYSTEM, + IfMatch, + Only, + always, + if_absent, +) + +if TYPE_CHECKING: + from collections.abc import ( + AsyncIterator, + Buffer, + Callable, + Iterable, + Iterator, + Mapping, + Sequence, + ) + + from obstore import GetOptions, GetResult, ListResult, ListStream, ObjectMeta, PutMode + from obstore.store import ObjectStore + + from zarr_storage.experimental._types import ByteRange, Copied, ListItem + +__all__ = ["ObjectStoreBackend"] + +R = TypeVar("R") + +_EMPTY = memoryview(b"") + +_NOT_A_DIRECTORY = f"(os error {errno.ENOTDIR})" +"""How a filesystem store's refusal reads when a parent of the path is a file.""" + +_PUT_ATTEMPTS = 16 +"""How many times a write starts over when the store refused it for a state that then went away.""" + + +# ---------------------------------------------------------------------------- locations + + +def _location(store: ObjectStore) -> Location: + """Where `store`'s keys live. Read once, when the backend is made: a `LocalStore`'s relative + prefix resolves against the working directory of that moment, as the store's own did.""" + if isinstance(store, LocalStore): + prefix = store.prefix + path = "" if prefix is None else Path(prefix).resolve().as_posix().strip("/") + return Location(LOCAL_FILESYSTEM, path) + if isinstance(store, HTTPStore): + scheme, host, path = _url_parts(store.url) + return Location(("http", scheme, host), path) + space = _cloud_space(store) + if space is not None: + prefix = cast("S3Store | GCSStore | AzureStore", store).prefix + return Location(space, "" if prefix is None else str(prefix).strip("/")) + return Location(Only(store), "") + + +def _cloud_space(store: ObjectStore) -> tuple[str, ...] | None: + """What names `store`'s bucket (or container); `None` for another kind of store, or a config + that doesn't say.""" + if not isinstance(store, (S3Store, GCSStore, AzureStore)): + return None + config = cast("Mapping[str, object]", store.config) + if isinstance(store, S3Store): + bucket, endpoint = config.get("bucket"), config.get("endpoint") + if bucket is None: + return None + server = ("", "", "") if endpoint is None else _url_parts(str(endpoint)) + return ("s3", *server, str(bucket)) + if isinstance(store, GCSStore): + bucket = config.get("bucket") + return None if bucket is None else ("gcs", str(bucket)) + account, container = config.get("account_name"), config.get("container_name") + if account is None or container is None: + return None + return ("azure", str(account), str(container)) + + +_DEFAULT_PORTS = {"http": 80, "https": 443} + + +def _url_parts(url: str) -> tuple[str, str, str]: + """`url`'s scheme, host (with a port other than the scheme's default), and path, without the + user name, password, query or fragment, which may hold credentials (a presigned URL's + signature) and don't name data. The path is decoded and normalized, so it compares as keys + do.""" + parts = urlsplit(url) + scheme = parts.scheme.lower() + host = "" if parts.hostname is None else parts.hostname + if ":" in host: + host = f"[{host}]" # IPv6 + try: + port = parts.port + except ValueError: # not a number; keep it as written, minus any credentials + port, host = None, parts.netloc.rpartition("@")[2].lower() + if port is not None and port != _DEFAULT_PORTS.get(scheme): + host = f"{host}:{port}" + return scheme, host, _url_path(parts.path) + + +def _url_path(path: str) -> str: + """A URL path as a normalized directory: decoded, without empty or `.` segments, and with + `..` applied. A segment that decodes to a NUL, which no key holds, stays encoded.""" + segments: list[str] = [] + decoded = "/".join(raw if "\x00" in unquote(raw) else unquote(raw) for raw in path.split("/")) + for segment in decoded.split("/"): + if segment in ("", "."): + continue + if segment == "..": + if segments: + segments.pop() + continue + segments.append(segment) + return "/".join(segments) + + +# ---------------------------------------------------------------------------- generations + + +def _generation(e_tag: str | None, version: str | None) -> Generation: + return Generation(("obstore", e_tag, version)) + + +def _metadata(meta: ObjectMeta) -> ObjectMetadata: + return ObjectMetadata( + meta["size"], + _generation(meta["e_tag"], meta["version"]), + meta["last_modified"].timestamp(), + ) + + +def _version_of(generation: object) -> tuple[str | None, str | None] | None: + """The `(e_tag, version)` in a generation this backend minted, or `None` for any other.""" + match generation: + case ("obstore", str() | None as e_tag, str() | None as version): + return e_tag, version + case _: + return None + + +def _if_match_mode(generation: Generation) -> PutMode | None: + """The put mode that writes only over `generation`; `None` for a generation this backend did + not mint, which no stored value has.""" + version = _version_of(generation) + if version is None: + return None + e_tag, object_version = version + if e_tag is None and object_version is None: + raise UnsupportedOperationError( + "The store reported neither an ETag nor a version, so writes can't be conditional." + ) + mode = {k: v for k, v in (("e_tag", e_tag), ("version", object_version)) if v is not None} + return cast("PutMode", mode) + + +def _refuse(current: ObjectMetadata | Missing) -> Rejected | Missing: + """The outcome of a write conditioned on a generation this backend did not mint.""" + return current if isinstance(current, Missing) else Rejected(current.generation) + + +def _found(result: GetResult, data: memoryview) -> Found: + return Found(data, _generation(result.meta["e_tag"], result.meta["version"]), time.time()) + + +def _if_none_match(generation: Generation) -> GetOptions: + """Read options that skip the read if the value has `generation`, where the store can tell.""" + version = _version_of(generation) + if version is None or version[0] is None: + return {} + return {"if_none_match": version[0]} + + +# ---------------------------------------------------------------------------- reads + + +def _get_options(byte_range: ByteRange | None) -> GetOptions: + match byte_range: + case None: + return {} + case RangeRequest(start=start, end=end): + return {"range": (start, end)} + case OffsetRequest(start=start): + return {"range": {"offset": start}} + case SuffixRequest(length=length): + return {"range": {"suffix": length}} + + +def _is_empty_request(byte_range: ByteRange | None) -> bool: + """Whether the range selects no bytes regardless of the value (object stores refuse those).""" + match byte_range: + case RangeRequest(start=start, end=end): + return start == end + case SuffixRequest(length=0): + return True + case _: + return False + + +def _empty_read_or_raise( + meta: ObjectMetadata | Missing, byte_range: ByteRange | None, error: BaseException | None +) -> Found | Missing: + """The result of a read the object store refused or that selects nothing. + + Object stores refuse a range that starts at the end of the value; the contract reads that as + empty. A range past the end raises `InvalidByteRangeError` (from `resolve`). Any other refusal + re-raises the store's error. + """ + if isinstance(meta, Missing): + return meta + start, end = resolve(byte_range, meta.size) + if start == end: + return Found(_EMPTY, meta.generation, time.time()) + if error is not None: + raise error + raise AssertionError("A non-empty range was treated as empty.") + + +def _pinned(generation: Generation) -> GetOptions | None: + """Read options that make a read fail unless the value still has `generation`. + + `None` when the store reported neither an ETag nor a version, so reads can't be pinned. + """ + version = _version_of(generation) + if version is None: + return None + e_tag, object_version = version + if e_tag is not None: + return {"if_match": e_tag} + if object_version is not None: + return {"version": object_version} + return None + + +def _slices(data: memoryview, ranges: Sequence[ByteRange]) -> tuple[memoryview, ...]: + return tuple(data[slice(*resolve(r, len(data)))] for r in ranges) + + +# ---------------------------------------------------------------------------- listing + +# obstore's `list` overloads mention Arrow types from an optional dependency, which pyright can't +# resolve without it; these wrappers pin the non-Arrow overload in one place. + + +def _list(store: ObjectStore, prefix: str | None) -> ListStream[Sequence[ObjectMeta]]: + return obstore.list(store, prefix, return_arrow=False) # pyright: ignore[reportUnknownMemberType] + + +def _list_with_delimiter( + store: ObjectStore, prefix: str | None +) -> ListResult[Sequence[ObjectMeta]]: + return obstore.list_with_delimiter(store, prefix, return_arrow=False) # pyright: ignore[reportUnknownMemberType] + + +async def _list_with_delimiter_async( + store: ObjectStore, prefix: str | None +) -> ListResult[Sequence[ObjectMeta]]: + return await obstore.list_with_delimiter_async(store, prefix, return_arrow=False) # pyright: ignore[reportUnknownMemberType] + + +def _prefix(directory: str) -> str | None: + return None if directory == "" else directory + + +def _valid_keys(paths: Iterable[str], directory: str) -> Iterator[str]: + """The paths that follow the key grammar and lie strictly under `directory`.""" + for path in paths: + if path == directory: + continue + try: + yield check_key(path) + except InvalidKeyError: + continue + + +def _children( + objects: Iterable[ObjectMeta], prefixes: Iterable[str], directory: str +) -> list[ListItem]: + items: list[ListItem] = [ + Key(relativize(path, directory)) + for path in _valid_keys((m["path"] for m in objects), directory) + ] + items.extend(Prefix(relativize(p.removesuffix("/"), directory)) for p in prefixes) + return items + + +def _ancestors(path: str) -> list[str]: + """`path`'s parent directories, nearest last: `a/b/c` gives `a`, `a/b`.""" + segments = path.split("/") + return ["/".join(segments[:i]) for i in range(1, len(segments))] + + +class ObjectStoreBackend: + """Keys stored in an obstore store. + + Generations are the store's ETag and version. `put_if_match` needs a store that supports it (S3, + GCS, Azure and obstore's `MemoryStore` do; obstore's `LocalStore` doesn't); otherwise it raises + `UnsupportedOperationError`. Object stores can't delete conditionally, so this backend has no + `delete_if_match`. `get_if_changed` sends `If-None-Match` with the generation's ETag. + + `get_ranges` reads the first range, then the others pinned (`If-Match`) to the generation and + size that first response reported. If the value changed in between, or the store reports + neither ETags nor versions, it reads the value once, whole, and slices it. + + obstore's `LocalStore` refuses paths that lie under a file; for it alone, such a refusal reads + as an absent key. Every other store's errors are raised. obstore's `LocalStore` has no locking, + so concurrent writes that create and remove the same directories can still surface its + errors; `LocalBackend` is the backend for that. + + Parameters + ---------- + store + The obstore store. + writable + Whether to accept writes. Defaults to `False` for `HTTPStore`, `True` otherwise. + """ + + def __init__( + self, + store: ObjectStore, + *, + writable: bool | None = None, + ) -> None: + self._store = store + self._writable = not isinstance(store, HTTPStore) if writable is None else writable + # Only a filesystem refuses a path that lies under a file; elsewhere a refusal is an error. + self._filesystem = isinstance(store, LocalStore) + self._location = _location(store) + self._closed = False + + def __getstate__(self) -> dict[str, object]: + # The location is recomputed on unpickling: an unpickled `LocalStore` resolves a relative + # prefix again, against the receiving process's working directory. + return {key: value for key, value in vars(self).items() if key != "_location"} + + def __setstate__(self, state: dict[str, object]) -> None: + vars(self).update(state) + self._location = _location(self._store) + + @property + def store(self) -> ObjectStore: + """The obstore store.""" + return self._store + + @property + def resource_key(self) -> str: + """`"obstore."` and the store's class name, so that, for instance, every S3 backend shares + one limit by default, as TensorStore's `s3_request_concurrency` does.""" + return f"obstore.{type(self._store).__name__}" + + def __repr__(self) -> str: + return f"ObjectStoreBackend({self._store!r})" + + # --- Backend + + @property + def location(self) -> Location: + """The bucket (or account and container, or URL) and prefix the store reads; obstore's + `LocalStore` shares the local filesystem's space with `LocalBackend`. A store of a kind it + doesn't know, and a `MemoryStore`, is a space of its own.""" + return self._location + + @property + def closed(self) -> bool: + return self._closed + + @property + def writable(self) -> bool: + return self._writable + + def close(self) -> None: + self._closed = True + + # --- "absent" for filesystem-backed stores, which refuse paths under a file + + def _under_a_key(self, path: str) -> bool: + """Whether this is a filesystem store and a parent of `path` is a key.""" + return self._filesystem and any(self._head_raw(p) is not None for p in _ancestors(path)) + + async def _under_a_key_async(self, path: str) -> bool: + if not self._filesystem: + return False + for p in _ancestors(path): + if await self._head_raw_async(p) is not None: + return True + return False + + def _refused_under_a_key(self, error: GenericError, path: str) -> bool: + """Whether a filesystem store refused `path` because a parent of it is a key. + + `ENOTDIR` in the refusal says so as of the refusal. Looking at the parents afterwards can + race a concurrent delete of that parent, so that is only the fallback. + """ + return self._filesystem and (_NOT_A_DIRECTORY in str(error) or self._under_a_key(path)) + + async def _refused_under_a_key_async(self, error: GenericError, path: str) -> bool: + return self._filesystem and ( + _NOT_A_DIRECTORY in str(error) or await self._under_a_key_async(path) + ) + + def _blocked_by_a_key(self, directory: str) -> bool: + """Whether a filesystem store refused to list `directory` because it is, or lies under, a key.""" + return self._filesystem and ( + self._head_raw(directory) is not None or self._under_a_key(directory) + ) + + async def _blocked_by_a_key_async(self, directory: str) -> bool: + return self._filesystem and ( + await self._head_raw_async(directory) is not None + or await self._under_a_key_async(directory) + ) + + def _head_raw(self, path: str) -> ObjectMetadata | None: + try: + return _metadata(obstore.head(self._store, path)) + except (FileNotFoundError, GenericError): + return None + + async def _head_raw_async(self, path: str) -> ObjectMetadata | None: + try: + return _metadata(await obstore.head_async(self._store, path)) + except (FileNotFoundError, GenericError): + return None + + def _is_directory(self, path: str) -> bool: + """Whether `path` is a directory, on a filesystem store (even one holding only uploads).""" + if not isinstance(self._store, LocalStore) or self._store.prefix is None: + return False + return (Path(self._store.prefix) / path).is_dir() + + def _reclaim_empty_directory(self, path: str) -> bool: + """Remove a directory at `path` that holds no files, on a filesystem store. + + obstore's `LocalStore` leaves the directories of deleted keys behind, and one in the way of a + key would otherwise make the write fail. Only empty directories are removed, with `rmdir`, + deepest first; `rmdir` refuses a directory a writer has just added to, so this never removes + a key. Returns whether the directory is gone. + """ + if not isinstance(self._store, LocalStore) or self._store.prefix is None: + return False + return _remove_empty_directories(Path(self._store.prefix) / path) + + def _conflicts(self, path: str) -> bool: + """Whether this is a filesystem store and `path` collides with a key or a directory. + + Answers `False` if the check itself fails, so the caller raises the write's own error. + """ + if not self._filesystem: + return False + try: + if self._under_a_key(path): + return True + listed = _list_with_delimiter(self._store, path) + except Exception: # noqa: BLE001 -- only a diagnosis; the write's error is raised instead + return False + return len(listed["objects"]) > 0 or len(listed["common_prefixes"]) > 0 + + async def _conflicts_async(self, path: str) -> bool: + if not self._filesystem: + return False + try: + if await self._under_a_key_async(path): + return True + listed = await _list_with_delimiter_async(self._store, path) + except Exception: # noqa: BLE001 -- only a diagnosis; the write's error is raised instead + return False + return len(listed["objects"]) > 0 or len(listed["common_prefixes"]) > 0 + + # --- Readable + + def head(self, path: str) -> ObjectMetadata | Missing: + try: + return _metadata(obstore.head(self._store, path)) + except FileNotFoundError: + return Missing(time.time()) + except GenericError as e: + if self._refused_under_a_key(e, path): + return Missing(time.time()) + raise + + async def head_async(self, path: str) -> ObjectMetadata | Missing: + try: + return _metadata(await obstore.head_async(self._store, path)) + except FileNotFoundError: + return Missing(time.time()) + except GenericError as e: + if await self._refused_under_a_key_async(e, path): + return Missing(time.time()) + raise + + def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + return self._get(path, byte_range, {}) + + async def get_async(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + return await self._get_async(path, byte_range, {}) + + def get_into(self, path: str, out: Buffer, byte_range: ByteRange | None) -> Copied | Missing: + """A read, copied into `out`: obstore can't read into a caller's buffer.""" + view = byte_view(out, writable=True) + return copy_into(self.get(path, byte_range), view) + + async def get_into_async( + self, path: str, out: Buffer, byte_range: ByteRange | None + ) -> Copied | Missing: + view = byte_view(out, writable=True) + return copy_into(await self.get_async(path, byte_range), view) + + def get_if_changed( + self, path: str, generation: Generation, byte_range: ByteRange | None + ) -> Found | Missing | Unchanged: + try: + result = self._get(path, byte_range, _if_none_match(generation)) + except NotModifiedError: + return Unchanged(generation, time.time()) + return _unless_unchanged(result, generation) + + async def get_if_changed_async( + self, path: str, generation: Generation, byte_range: ByteRange | None + ) -> Found | Missing | Unchanged: + try: + result = await self._get_async(path, byte_range, _if_none_match(generation)) + except NotModifiedError: + return Unchanged(generation, time.time()) + return _unless_unchanged(result, generation) + + def _get(self, path: str, byte_range: ByteRange | None, options: GetOptions) -> Found | Missing: + """A read with extra `options`; raises `NotModifiedError` if they include a matching + `if_none_match`.""" + if _is_empty_request(byte_range): + return _empty_read_or_raise(self.head(path), byte_range, None) + try: + result = obstore.get(self._store, path, options={**options, **_get_options(byte_range)}) + except FileNotFoundError: + return Missing(time.time()) + except GenericError as e: + return _empty_read_or_raise(self.head(path), byte_range, e) + return _found(result, memoryview(result.bytes())) + + async def _get_async( + self, path: str, byte_range: ByteRange | None, options: GetOptions + ) -> Found | Missing: + if _is_empty_request(byte_range): + return _empty_read_or_raise(await self.head_async(path), byte_range, None) + try: + result = await obstore.get_async( + self._store, path, options={**options, **_get_options(byte_range)} + ) + except FileNotFoundError: + return Missing(time.time()) + except GenericError as e: + return _empty_read_or_raise(await self.head_async(path), byte_range, e) + return _found(result, memoryview(await result.bytes_async())) + + def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> FoundRanges | Missing: + if len(ranges) == 0 or _is_empty_request(ranges[0]): + return self._read_whole_and_slice(path, ranges) + try: + first = obstore.get(self._store, path, options=_get_options(ranges[0])) + except FileNotFoundError: + return Missing(time.time()) + except GenericError: + # The first range starts at the end of the value; one whole read answers every range. + return self._read_whole_and_slice(path, ranges) + meta = first.meta + generation = _generation(meta["e_tag"], meta["version"]) + pinned = _pinned(generation) + if pinned is None: + return self._read_whole_and_slice(path, ranges) + try: + rest = [self._read_pinned(path, pinned, *resolve(r, meta["size"])) for r in ranges[1:]] + except (PreconditionError, FileNotFoundError): + # The value changed after the first read; one whole read is consistent by itself. + return self._read_whole_and_slice(path, ranges) + return FoundRanges((memoryview(first.bytes()), *rest), generation, time.time()) + + def _read_pinned(self, path: str, pinned: GetOptions, start: int, end: int) -> memoryview: + if start == end: + return _EMPTY + result = obstore.get(self._store, path, options={**pinned, "range": (start, end)}) + _check_pinned(result.meta, pinned) + return memoryview(result.bytes()) + + def _read_whole_and_slice( + self, path: str, ranges: Sequence[ByteRange] + ) -> FoundRanges | Missing: + try: + result = obstore.get(self._store, path) + except FileNotFoundError: + return Missing(time.time()) + except GenericError as e: + if self._refused_under_a_key(e, path): + return Missing(time.time()) + raise + generation = _generation(result.meta["e_tag"], result.meta["version"]) + return FoundRanges(_slices(memoryview(result.bytes()), ranges), generation, time.time()) + + async def get_ranges_async( + self, path: str, ranges: Sequence[ByteRange] + ) -> FoundRanges | Missing: + if len(ranges) == 0 or _is_empty_request(ranges[0]): + return await self._read_whole_and_slice_async(path, ranges) + try: + first = await obstore.get_async(self._store, path, options=_get_options(ranges[0])) + except FileNotFoundError: + return Missing(time.time()) + except GenericError: + return await self._read_whole_and_slice_async(path, ranges) + meta = first.meta + generation = _generation(meta["e_tag"], meta["version"]) + pinned = _pinned(generation) + if pinned is None: + return await self._read_whole_and_slice_async(path, ranges) + try: + rest = await asyncio.gather( + *( + _read_pinned_async(self._store, path, pinned, *resolve(r, meta["size"])) + for r in ranges[1:] + ) + ) + except (PreconditionError, FileNotFoundError): + return await self._read_whole_and_slice_async(path, ranges) + return FoundRanges((memoryview(await first.bytes_async()), *rest), generation, time.time()) + + async def _read_whole_and_slice_async( + self, path: str, ranges: Sequence[ByteRange] + ) -> FoundRanges | Missing: + try: + result = await obstore.get_async(self._store, path) + except FileNotFoundError: + return Missing(time.time()) + except GenericError as e: + if await self._refused_under_a_key_async(e, path): + return Missing(time.time()) + raise + generation = _generation(result.meta["e_tag"], result.meta["version"]) + data = memoryview(await result.bytes_async()) + return FoundRanges(_slices(data, ranges), generation, time.time()) + + # --- Writable + + def put(self, path: str, value: memoryview) -> Written: + return self._put(path, value, None, always) + + async def put_async(self, path: str, value: memoryview) -> Written: + return await self._put_async(path, value, None, always) + + def put_if_absent(self, path: str, value: memoryview) -> Written | Rejected: + return self._put(path, value, "create", if_absent) + + async def put_if_absent_async(self, path: str, value: memoryview) -> Written | Rejected: + return await self._put_async(path, value, "create", if_absent) + + def put_if_match( + self, path: str, value: memoryview, generation: Generation + ) -> Written | Rejected | Missing: + mode = _if_match_mode(generation) + if mode is None: + return _refuse(self.head(path)) + return self._put(path, value, mode, IfMatch(generation)) + + async def put_if_match_async( + self, path: str, value: memoryview, generation: Generation + ) -> Written | Rejected | Missing: + mode = _if_match_mode(generation) + if mode is None: + return _refuse(await self.head_async(path)) + return await self._put_async(path, value, mode, IfMatch(generation)) + + def _put( + self, + path: str, + value: memoryview, + mode: PutMode | None, + check: Callable[[Generation | None], R | None], + ) -> Written | R: + """Write with `mode`. When the store refuses, `check` the key's current generation: its + refusal is the outcome, and if it has none, the state that made the store refuse went away + and the write starts over.""" + for _ in range(_PUT_ATTEMPTS): + try: + # obstore keeps a reference to the buffer it's given; copy so later changes to the + # caller's buffer don't reach the stored value. + result = obstore.put(self._store, path, bytes(value), mode=mode) + except (AlreadyExistsError, PreconditionError): + current = self.head(path) + if isinstance(current, Missing): + if self._reclaim_empty_directory(path): + continue + if self._conflicts(path): + raise _conflict(path, self._store) from None + refusal = check(None if isinstance(current, Missing) else current.generation) + if refusal is not None: + return refusal + continue + except NotImplementedError as e: + raise UnsupportedOperationError( + f"{self._store!r} does not support this conditional write." + ) from e + except GenericError as e: + if self._reclaim_empty_directory(path): + continue + if self._conflicts(path) or self._is_directory(path): + raise _conflict(path, self._store) from e + raise + return Written(_generation(result["e_tag"], result["version"])) + raise OSError(f"Gave up writing {path!r}: the store kept refusing it.") + + async def _put_async( + self, + path: str, + value: memoryview, + mode: PutMode | None, + check: Callable[[Generation | None], R | None], + ) -> Written | R: + for _ in range(_PUT_ATTEMPTS): + try: + result = await obstore.put_async(self._store, path, bytes(value), mode=mode) + except (AlreadyExistsError, PreconditionError): + current = await self.head_async(path) + if isinstance(current, Missing): + if await asyncio.to_thread(self._reclaim_empty_directory, path): + continue + if await self._conflicts_async(path): + raise _conflict(path, self._store) from None + refusal = check(None if isinstance(current, Missing) else current.generation) + if refusal is not None: + return refusal + continue + except NotImplementedError as e: + raise UnsupportedOperationError( + f"{self._store!r} does not support this conditional write." + ) from e + except GenericError as e: + if await asyncio.to_thread(self._reclaim_empty_directory, path): + continue + if await self._conflicts_async(path) or await asyncio.to_thread( + self._is_directory, path + ): + raise _conflict(path, self._store) from e + raise + return Written(_generation(result["e_tag"], result["version"])) + raise OSError(f"Gave up writing {path!r}: the store kept refusing it.") + + def delete(self, path: str) -> Deleted | Missing: + meta = self.head(path) + if isinstance(meta, Missing): + return meta + try: + obstore.delete(self._store, path) + except FileNotFoundError: + return Missing(time.time()) + return Deleted(meta.generation) + + async def delete_async(self, path: str) -> Deleted | Missing: + meta = await self.head_async(path) + if isinstance(meta, Missing): + return meta + try: + await obstore.delete_async(self._store, path) + except FileNotFoundError: + return Missing(time.time()) + return Deleted(meta.generation) + + def delete_dir(self, directory: str) -> None: + paths = list(self._paths(directory)) + try: + if paths: + obstore.delete(self._store, paths) + except FileNotFoundError: + # A concurrent delete removed some first; delete the rest one at a time. + for path in paths: + with contextlib.suppress(FileNotFoundError): + obstore.delete(self._store, path) + + async def delete_dir_async(self, directory: str) -> None: + paths = [path async for path in self._paths_async(directory)] + try: + if paths: + await obstore.delete_async(self._store, paths) + except FileNotFoundError: + for path in paths: + with contextlib.suppress(FileNotFoundError): + await obstore.delete_async(self._store, path) + + # --- Listable + + def _paths(self, directory: str) -> Iterator[str]: + """Every stored path under `directory`, whether or not it follows the key grammar.""" + try: + for chunk in _list(self._store, _prefix(directory)): + yield from (meta["path"] for meta in chunk if meta["path"] != directory) + except GenericError: + # A filesystem store can't walk a path that is, or lies under, a file; such a + # directory has no children. + if not self._blocked_by_a_key(directory): + raise + + async def _paths_async(self, directory: str) -> AsyncIterator[str]: + try: + async for chunk in _list(self._store, _prefix(directory)): + for meta in chunk: + if meta["path"] != directory: + yield meta["path"] + except GenericError: + if not await self._blocked_by_a_key_async(directory): + raise + + def list(self, directory: str) -> Iterator[str]: + return _valid_keys(self._paths(directory), directory) + + async def list_async(self, directory: str) -> AsyncIterator[str]: + async for path in self._paths_async(directory): + for key in _valid_keys([path], directory): + yield key + + def list_dir(self, directory: str) -> Iterator[ListItem]: + try: + result = _list_with_delimiter(self._store, _prefix(directory)) + except GenericError: + if not self._blocked_by_a_key(directory): + raise + return iter(()) + return iter(_children(result["objects"], result["common_prefixes"], directory)) + + async def list_dir_async(self, directory: str) -> AsyncIterator[ListItem]: + try: + result = await _list_with_delimiter_async(self._store, _prefix(directory)) + except GenericError: + if not await self._blocked_by_a_key_async(directory): + raise + return + for item in _children(result["objects"], result["common_prefixes"], directory): + yield item + + +async def _read_pinned_async( + store: ObjectStore, path: str, pinned: GetOptions, start: int, end: int +) -> memoryview: + if start == end: + return _EMPTY + result = await obstore.get_async(store, path, options={**pinned, "range": (start, end)}) + _check_pinned(result.meta, pinned) + return memoryview(await result.bytes_async()) + + +def _check_pinned(meta: ObjectMeta, pinned: GetOptions) -> None: + """Treat a response from another generation as a failed precondition. + + A store that ignored `If-Match` would otherwise mix parts of two values. + """ + if meta["e_tag"] != pinned.get("if_match", meta["e_tag"]) or meta["version"] != pinned.get( + "version", meta["version"] + ): + raise PreconditionError("The value changed between reads.") + + +def _remove_empty_directories(target: Path) -> bool: + """Remove `target` and the directories under it if none holds a file; whether it is gone.""" + if not target.is_dir(): + return False + try: + for directory, _, files in os.walk(target, topdown=False): + if files: + return False + os.rmdir(directory) + except FileNotFoundError: + return not target.exists() + except NotADirectoryError: + return False # A key was written in the directory's place meanwhile. + except OSError as e: + if e.errno == errno.ENOTEMPTY: + return False + raise + return True + + +def _unless_unchanged( + result: Found | Missing, generation: Generation +) -> Found | Missing | Unchanged: + """`Unchanged` for a value read whole although it has `generation`. + + That happens when the store can't skip the read (it ignores `If-None-Match`); the bytes are + discarded so the outcome doesn't depend on the store. A generation with neither an ETag nor a + version identifies no value (an HTTP server that sends neither gives every value that one), so + a read of it is never `Unchanged`. + """ + if ( + isinstance(result, Found) + and result.generation == generation + and _version_of(generation) not in (None, (None, None)) + ): + return Unchanged(generation, result.read_at) + return result + + +def _conflict(path: str, store: ObjectStore) -> KeyConflictError: + return KeyConflictError( + f"{path!r} collides with a directory or key of the same name, which {store!r} can't hold " + "side by side." + ) diff --git a/packages/zarr-storage/src/zarr_storage/experimental/testing/__init__.py b/packages/zarr-storage/src/zarr_storage/experimental/testing/__init__.py new file mode 100644 index 0000000000..b184ea5a4b --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/testing/__init__.py @@ -0,0 +1,38 @@ +"""The conformance suite every backend runs. + +A backend's test class subclasses `StoreSuite` and overrides `make_store` to return an empty, +writable `Store` over a fresh backend; it adds the mixin for each optional capability the backend has +(`ConditionalPutSuite`, `ConditionalDeleteSuite`, `ConditionalRaceSuite`, `KeyAndDirectorySuite`, +`PickleSuite`, `UniqueGenerationsSuite`) or the one +that checks it refuses it cleanly (`NoConditionalPutSuite`, +`KeyDirectoryConflictSuite`). Every test runs through the sync methods and again through the async +methods. Install the `testing` extra for pytest and Hypothesis. +""" + +from zarr_storage.experimental.testing._api import AsyncAPI, FullBackend, StoreAPI +from zarr_storage.experimental.testing._suite import ( + ConditionalDeleteSuite, + ConditionalPutSuite, + ConditionalRaceSuite, + KeyAndDirectorySuite, + KeyDirectoryConflictSuite, + NoConditionalPutSuite, + PickleSuite, + StoreSuite, + UniqueGenerationsSuite, +) + +__all__ = [ + "AsyncAPI", + "ConditionalDeleteSuite", + "ConditionalPutSuite", + "ConditionalRaceSuite", + "FullBackend", + "KeyAndDirectorySuite", + "KeyDirectoryConflictSuite", + "NoConditionalPutSuite", + "PickleSuite", + "StoreAPI", + "StoreSuite", + "UniqueGenerationsSuite", +] diff --git a/packages/zarr-storage/src/zarr_storage/experimental/testing/_api.py b/packages/zarr-storage/src/zarr_storage/experimental/testing/_api.py new file mode 100644 index 0000000000..65acabd7e2 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/testing/_api.py @@ -0,0 +1,262 @@ +"""The store surface the suite tests, and an adapter that drives it through `AsyncStore`. + +Every suite test runs twice: once against `Store`, once against `AsyncAPI`, which gives the same +sync-looking surface but performs every call through the `AsyncStore` method of the same name on +one event loop. The sync and async surfaces therefore meet one contract, checked by one set of tests. +""" + +from __future__ import annotations + +from collections.abc import Buffer +from typing import TYPE_CHECKING, Protocol, Self, TypeVar, cast + +from zarr_storage.experimental._protocols import ( + Listable, + Readable, + ReadableInto, + Writable, + WritableIfMatch, +) +from zarr_storage.experimental._store import AsyncStore + +if TYPE_CHECKING: + import asyncio + from collections.abc import AsyncIterator, Iterable, Iterator, Sequence + from types import TracebackType + + from zarr_storage.experimental._protocols import DeletableIfMatch, DeletableIfMatchAsync + from zarr_storage.experimental._store import Store + from zarr_storage.experimental._types import ( + ByteRange, + Copied, + Deleted, + Found, + FoundRanges, + Generation, + ListItem, + Missing, + ObjectMetadata, + Rejected, + Unchanged, + Written, + ) + +__all__ = ["AsyncAPI", "FullBackend", "StoreAPI", "async_api", "delete_if_match", "unwrap"] + +T = TypeVar("T") +Q = TypeVar("Q", bound="str | tuple[str, ByteRange | None]") + + +class FullBackend( + Readable, + ReadableInto[Buffer], + Writable, + WritableIfMatch, + Listable, + Protocol, +): + """A backend with every capability the suite needs of all backends. + + Only the sync protocols: `AsyncStore` uses a backend's async twins where it has them and runs + its sync methods on its context's thread pool otherwise, so the suite's async run covers both. + `DeletableIfMatch` is left out, since object stores lack it; `delete_if_match` reaches it. + """ + + +class StoreAPI(Protocol): + """The operations the suite calls; `Store` and `AsyncAPI` both provide them.""" + + @property + def root(self) -> str: ... + @property + def read_only(self) -> bool: ... + @property + def closed(self) -> bool: ... + + def get(self, key: str, *, byte_range: ByteRange | None = None) -> Found | Missing: ... + def get_if_changed( + self, key: str, generation: Generation, *, byte_range: ByteRange | None = None + ) -> Found | Missing | Unchanged: ... + def get_ranges(self, key: str, ranges: Sequence[ByteRange]) -> FoundRanges | Missing: ... + def get_into( + self, key: str, out: Buffer, *, byte_range: ByteRange | None = None + ) -> Copied | Missing: ... + def head(self, key: str) -> ObjectMetadata | Missing: ... + def exists(self, key: str) -> bool: ... + def put(self, key: str, value: Buffer) -> Written: ... + def put_if_absent(self, key: str, value: Buffer) -> Written | Rejected: ... + def put_if_match( + self, key: str, value: Buffer, generation: Generation + ) -> Written | Rejected | Missing: ... + def delete(self, key: str) -> Deleted | Missing: ... + def delete_dir(self, directory: str = "") -> None: ... + def get_many(self, requests: Iterable[Q]) -> Iterator[tuple[Q, Found | Missing]]: ... + def get_into_many( + self, requests: Iterable[tuple[str, Buffer] | tuple[str, Buffer, ByteRange | None]] + ) -> Iterator[ + tuple[tuple[str, Buffer] | tuple[str, Buffer, ByteRange | None], Copied | Missing] + ]: ... + def put_many(self, items: Iterable[tuple[str, Buffer]]) -> list[tuple[str, Written]]: ... + def delete_many(self, keys: Iterable[str]) -> list[tuple[str, Deleted | Missing]]: ... + def list(self, directory: str = "") -> Iterator[str]: ... + def list_dir(self, directory: str = "") -> Iterator[ListItem]: ... + def __truediv__(self, directory: str) -> Self: ... + def as_read_only(self) -> Self: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: ... + + +def unwrap(store: StoreAPI) -> Store[FullBackend]: + """The `Store` behind a `StoreAPI`: a sync view of an `AsyncAPI`'s store.""" + if isinstance(store, AsyncAPI): + return store.store.as_sync() + return store # pyright: ignore[reportReturnType] + + +def delete_if_match( + store: StoreAPI, key: str, generation: Generation +) -> Deleted | Rejected | Missing: + """`delete_if_match` through `store`'s surface, for a backend that has it.""" + if isinstance(store, AsyncAPI): + return store.delete_if_match(key, generation) + return cast("Store[DeletableIfMatch]", store).delete_if_match(key, generation) + + +async def _next(items: AsyncIterator[T]) -> T: + return await anext(items) + + +def async_api(store: Store[FullBackend], runner: asyncio.Runner) -> AsyncAPI: + """An `AsyncAPI` over an `AsyncStore` that owns `store`'s backend, at the backend's root, where + `make_store`'s stores are.""" + return AsyncAPI( + AsyncStore(store.backend, read_only=store.read_only, context=store.context), runner + ) + + +class AsyncAPI: + """`Store`'s surface, performed through an `AsyncStore` on one event loop. + + Each method runs the `AsyncStore` method of the same name to completion; listings and lazy + batches are taken one item per run. + """ + + def __init__(self, store: AsyncStore[FullBackend], runner: asyncio.Runner) -> None: + self._store = store + self._runner = runner + + @property + def store(self) -> AsyncStore[FullBackend]: + return self._store + + @property + def root(self) -> str: + return self._store.root + + @property + def read_only(self) -> bool: + return self._store.read_only + + @property + def closed(self) -> bool: + return self._store.closed + + def get(self, key: str, *, byte_range: ByteRange | None = None) -> Found | Missing: + return self._runner.run(self._store.get(key, byte_range=byte_range)) + + def get_if_changed( + self, key: str, generation: Generation, *, byte_range: ByteRange | None = None + ) -> Found | Missing | Unchanged: + return self._runner.run(self._store.get_if_changed(key, generation, byte_range=byte_range)) + + def get_ranges(self, key: str, ranges: Sequence[ByteRange]) -> FoundRanges | Missing: + return self._runner.run(self._store.get_ranges(key, ranges)) + + def get_into( + self, key: str, out: Buffer, *, byte_range: ByteRange | None = None + ) -> Copied | Missing: + return self._runner.run(self._store.get_into(key, out, byte_range=byte_range)) + + def head(self, key: str) -> ObjectMetadata | Missing: + return self._runner.run(self._store.head(key)) + + def exists(self, key: str) -> bool: + return self._runner.run(self._store.exists(key)) + + def put(self, key: str, value: Buffer) -> Written: + return self._runner.run(self._store.put(key, value)) + + def put_if_absent(self, key: str, value: Buffer) -> Written | Rejected: + return self._runner.run(self._store.put_if_absent(key, value)) + + def put_if_match( + self, key: str, value: Buffer, generation: Generation + ) -> Written | Rejected | Missing: + return self._runner.run(self._store.put_if_match(key, value, generation)) + + def delete(self, key: str) -> Deleted | Missing: + return self._runner.run(self._store.delete(key)) + + def delete_if_match(self, key: str, generation: Generation) -> Deleted | Rejected | Missing: + store = cast("AsyncStore[DeletableIfMatchAsync]", self._store) + return self._runner.run(store.delete_if_match(key, generation)) + + def delete_dir(self, directory: str = "") -> None: + self._runner.run(self._store.delete_dir(directory)) + + def get_many(self, requests: Iterable[Q]) -> Iterator[tuple[Q, Found | Missing]]: + # `get_many` checks its requests when called; the results come one at a time. + return self._iterate(self._store.get_many(requests)) + + def get_into_many( + self, requests: Iterable[tuple[str, Buffer] | tuple[str, Buffer, ByteRange | None]] + ) -> Iterator[ + tuple[tuple[str, Buffer] | tuple[str, Buffer, ByteRange | None], Copied | Missing] + ]: + return self._iterate(self._store.get_into_many(requests)) + + def put_many(self, items: Iterable[tuple[str, Buffer]]) -> list[tuple[str, Written]]: + return self._runner.run(self._store.put_many(items)) + + def delete_many(self, keys: Iterable[str]) -> list[tuple[str, Deleted | Missing]]: + return self._runner.run(self._store.delete_many(keys)) + + def list(self, directory: str = "") -> Iterator[str]: + # `list` checks its argument when called; the items come one at a time. + return self._iterate(self._store.list(directory)) + + def list_dir(self, directory: str = "") -> Iterator[ListItem]: + return self._iterate(self._store.list_dir(directory)) + + def _iterate(self, items: AsyncIterator[T]) -> Iterator[T]: + while True: + try: + yield self._runner.run(_next(items)) + except StopAsyncIteration: + return + + def __truediv__(self, directory: str) -> Self: + return type(self)(self._store / directory, self._runner) + + def as_read_only(self) -> Self: + return type(self)(self._store.as_read_only(), self._runner) + + def close(self) -> None: + self._runner.run(self._store.aclose()) + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() diff --git a/packages/zarr-storage/src/zarr_storage/experimental/testing/_stateful.py b/packages/zarr-storage/src/zarr_storage/experimental/testing/_stateful.py new file mode 100644 index 0000000000..967305c807 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/testing/_stateful.py @@ -0,0 +1,357 @@ +"""A Hypothesis state machine that checks a store against a dict model. + +Each step reads or writes through a view at a random root, so roots, views and the key grammar are +exercised together with the operations. Half the time a step targets a key the model holds, so +deletes, conditional writes and batches meet present keys, not just absent ones. Generations that a write or +delete retired are kept and replayed as preconditions: a backend must never hand one out again. +After every step the machine checks that listing, reading and metadata agree with the model. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from hypothesis import strategies as st +from hypothesis.stateful import RuleBasedStateMachine, initialize, invariant, precondition, rule + +from zarr_storage.experimental._errors import BatchError, KeyConflictError +from zarr_storage.experimental._keys import join +from zarr_storage.experimental._types import ( + Deleted, + Found, + Generation, + Key, + Missing, + ObjectMetadata, + Prefix, + Rejected, + Unchanged, + Written, +) +from zarr_storage.experimental.testing._api import delete_if_match + +if TYPE_CHECKING: + from collections.abc import Callable + + from zarr_storage.experimental._types import ListItem + from zarr_storage.experimental.testing._api import StoreAPI + +__all__ = ["Capabilities", "StoreMachine"] + +SEGMENTS = ["a", "b", "ab"] +ROOT_CHOICES = ["", "a", "a/b", "b"] +KEYS = st.lists(st.sampled_from(SEGMENTS), min_size=1, max_size=3).map("/".join) +ROOTS = st.sampled_from(ROOT_CHOICES) +DIRECTORIES = st.lists(st.sampled_from(SEGMENTS), max_size=2).map("/".join) +VALUES = st.binary(max_size=6) + + +@dataclass(frozen=True) +class Capabilities: + """What the backend under test supports; the machine expects refusals for the rest.""" + + conditional_put: bool + conditional_delete: bool + holds_key_and_directory: bool + leaves_empty_directories: bool + """Whether `list_dir` may report a `Prefix` for a directory a delete left empty.""" + unique_generations: bool + """Whether the backend never hands out a generation twice, even after a delete.""" + + +def _under(path: str, directory: str) -> bool: + return directory == "" or path.startswith(f"{directory}/") + + +def _nested(a: str, b: str) -> bool: + """Whether one of two distinct keys lies under the other.""" + return _under(a, b) or _under(b, a) + + +def _relative(path: str, root: str) -> str: + return path.removeprefix(f"{root}/") if root else path + + +class StoreMachine(RuleBasedStateMachine): + """Operations on one store, compared with a dict from key to value and generation.""" + + def __init__(self, make_store: Callable[[], StoreAPI], capabilities: Capabilities) -> None: + super().__init__() + self._make_store = make_store + self._capabilities = capabilities + self.values: dict[str, bytes] = {} + self.generations: dict[str, Generation] = {} + self.retired: list[Generation] = [] + + @initialize() + def open_store(self) -> None: + self.store = self._make_store() + + # --- model helpers + + def _target(self, data: st.DataObject) -> tuple[str, str]: + """A `(root, key)` to operate on: half the time a key the model holds.""" + if self.values and data.draw(st.booleans(), label="existing key"): + path = data.draw(st.sampled_from(sorted(self.values)), label="path") + roots = [r for r in ROOT_CHOICES if r == "" or path.startswith(f"{r}/")] + root = data.draw(st.sampled_from(roots), label="root") + return root, _relative(path, root) + return data.draw(ROOTS, label="root"), data.draw(KEYS, label="key") + + def _conflicts(self, path: str) -> bool: + """Whether writing `path` collides with a stored key, on a backend that can't hold both.""" + if self._capabilities.holds_key_and_directory: + return False + return any(_under(path, k) or _under(k, path) for k in self.values if k != path) + + def _expect_conflict(self, root: str, key: str, value: bytes) -> None: + """A write to a path that collides with a stored key raises, whatever its preconditions.""" + try: + (self.store / root).put_if_match(key, value, Generation(object())) + except KeyConflictError: + return + raise AssertionError(f"put({join(root, key)!r}) should have raised KeyConflictError") + + def _refusal(self, path: str) -> Rejected | Missing: + """What a conditional write or delete whose precondition fails returns for `path`.""" + current = self.generations.get(path) + return Missing() if current is None else Rejected(current) + + def _check_refused(self, result: object, path: str) -> None: + expected = self._refusal(path) + if isinstance(expected, Missing): + assert isinstance(result, Missing), result + else: + assert result == expected + + def _batch_keys(self, data: st.DataObject, root: str) -> list[str]: + """Distinct keys under `root`, each half the time one the model holds.""" + held = [_relative(p, root) for p in sorted(self.values) if _under(p, root) and p != root] + keys = st.one_of(KEYS, st.sampled_from(held)) if held else KEYS + return data.draw(st.lists(keys, max_size=4, unique=True), label="keys") + + def _record(self, path: str, value: bytes, generation: Generation) -> None: + if self._capabilities.unique_generations: + assert generation not in self.retired, "a retired generation was handed out again" + assert generation != self.generations.get(path) + if path in self.generations: + self.retired.append(self.generations[path]) + self.values[path] = value + self.generations[path] = generation + + def _forget(self, path: str) -> None: + self.retired.append(self.generations.pop(path)) + del self.values[path] + + # --- writes + + @rule(data=st.data(), value=VALUES) + def put(self, data: st.DataObject, value: bytes) -> None: + root, key = self._target(data) + path = join(root, key) + if self._conflicts(path): + try: + (self.store / root).put(key, value) + except KeyConflictError: + return + raise AssertionError(f"put({path!r}) should have raised KeyConflictError") + result = (self.store / root).put(key, value) + self._record(path, value, result.generation) + + @rule(data=st.data(), value=VALUES) + def put_if_absent(self, data: st.DataObject, value: bytes) -> None: + root, key = self._target(data) + path = join(root, key) + if self._conflicts(path): + try: + (self.store / root).put_if_absent(key, value) + except KeyConflictError: + return + raise AssertionError(f"put_if_absent({path!r}) should have raised KeyConflictError") + result = (self.store / root).put_if_absent(key, value) + if path in self.values: + assert result == Rejected(self.generations[path]) + else: + assert isinstance(result, Written) + self._record(path, value, result.generation) + + @precondition(lambda self: self._capabilities.conditional_put) + @rule(data=st.data(), value=VALUES, stale=st.booleans()) + def put_if_match(self, data: st.DataObject, value: bytes, stale: bool) -> None: + root, key = self._target(data) + path = join(root, key) + if self._conflicts(path): + self._expect_conflict(root, key, value) + return + current = self.generations.get(path) + expected = Generation(object()) if stale or current is None else current + result = (self.store / root).put_if_match(key, value, expected) + if not stale and current is not None: + assert isinstance(result, Written) + self._record(path, value, result.generation) + else: + self._check_refused(result, path) + + @precondition( + lambda self: ( + self._capabilities.conditional_put + and self._capabilities.unique_generations + and len(self.retired) > 0 + ) + ) + @rule(data=st.data(), value=VALUES) + def put_if_match_retired(self, data: st.DataObject, value: bytes) -> None: + """A generation a write or delete retired never matches again.""" + root, key = self._target(data) + if self._conflicts(join(root, key)): + self._expect_conflict(root, key, value) + return + retired = data.draw(st.sampled_from(self.retired), label="retired generation") + result = (self.store / root).put_if_match(key, value, retired) + self._check_refused(result, join(root, key)) + + @rule(data=st.data()) + def put_many(self, data: st.DataObject) -> None: + root = data.draw(ROOTS, label="root") + keys = self._batch_keys(data, root) + if not self._capabilities.holds_key_and_directory: + # Which of two nested keys in one batch lands is a race between threads, and a model + # that depends on it breaks Hypothesis's replays; `KeyDirectoryConflictSuite` checks it. + keys = [k for i, k in enumerate(keys) if not any(_nested(k, o) for o in keys[:i])] + items = [(key, data.draw(VALUES, label="value")) for key in keys] + paths = [join(root, key) for key in keys] + may_conflict = any(self._conflicts(path) for path in paths) + failure: BatchError | None = None + try: + written = (self.store / root).put_many(items) + except BatchError as error: + failure = error + written = [(str(key), result) for key, result in error.completed] + if failure is None: + assert [key for key, _ in written] == keys + else: + # Only a collision can fail a write here; the writes that landed are kept. + assert may_conflict, failure + assert all(isinstance(e, KeyConflictError) for e in failure.exceptions), failure + assert len(failure.completed) + len(failure.remaining) == len(items) + values = dict(items) + for key, result in written: + assert isinstance(result, Written) + self._record(join(root, key), values[key], result.generation) + + @rule(data=st.data()) + def delete_many(self, data: st.DataObject) -> None: + root = data.draw(ROOTS, label="root") + keys = self._batch_keys(data, root) + results = (self.store / root).delete_many(keys) + assert [key for key, _ in results] == keys + for key, result in results: + path = join(root, key) + if path in self.values: + assert result == Deleted(self.generations[path]) + self._forget(path) + else: + assert isinstance(result, Missing) + + @rule(data=st.data()) + def delete(self, data: st.DataObject) -> None: + root, key = self._target(data) + path = join(root, key) + result = (self.store / root).delete(key) + if path in self.values: + assert result == Deleted(self.generations[path]) + self._forget(path) + else: + assert isinstance(result, Missing) + + @precondition(lambda self: self._capabilities.conditional_delete) + @rule(data=st.data(), stale=st.booleans()) + def delete_if_match(self, data: st.DataObject, stale: bool) -> None: + root, key = self._target(data) + path = join(root, key) + current = self.generations.get(path) + expected = Generation(object()) if stale or current is None else current + result = delete_if_match(self.store / root, key, expected) + if not stale and current is not None: + assert result == Deleted(current) + self._forget(path) + else: + self._check_refused(result, path) + + @precondition( + lambda self: ( + self._capabilities.conditional_delete + and self._capabilities.unique_generations + and len(self.retired) > 0 + ) + ) + @rule(data=st.data()) + def delete_if_match_retired(self, data: st.DataObject) -> None: + root, key = self._target(data) + retired = data.draw(st.sampled_from(self.retired), label="retired generation") + result = delete_if_match(self.store / root, key, retired) + self._check_refused(result, join(root, key)) + + @rule(root=ROOTS, directory=DIRECTORIES) + def delete_dir(self, root: str, directory: str) -> None: + (self.store / root).delete_dir(directory) + target = join(root, directory) + for path in [p for p in self.values if p != target and _under(p, target)]: + self._forget(path) + + # --- reads, checked against the model + + @rule(root=ROOTS, directory=DIRECTORIES) + def list_view(self, root: str, directory: str) -> None: + view = self.store / root + under = join(root, directory) + expected = {_relative(p, root) for p in self.values if p != under and _under(p, under)} + listed = list(view.list(directory)) + assert len(listed) == len(set(listed)), "list reported a key twice" + assert set(listed) == expected + + @rule(root=ROOTS, directory=DIRECTORIES) + def list_dir_view(self, root: str, directory: str) -> None: + under = join(root, directory) + expected: set[ListItem] = set() + for path in self.values: + if path == under or not _under(path, under): + continue + name, sep, _ = _relative(path, under).partition("/") + expected.add(Prefix(name) if sep else Key(name)) + listed = list((self.store / root).list_dir(directory)) + assert len(listed) == len(set(listed)), "list_dir reported a child twice" + found = set(listed) + if self._capabilities.leaves_empty_directories: + found -= {item for item in found - expected if isinstance(item, Prefix)} + assert found == expected + + @invariant() + def reads_match_the_model(self) -> None: + if not hasattr(self, "store"): + return + assert set(self.store.list()) == set(self.values) + batch = dict(self.store.get_many(self.values)) + assert set(batch) == set(self.values) + for path, result in batch.items(): + assert isinstance(result, Found) + assert (bytes(result.value), result.generation) == ( + self.values[path], + self.generations[path], + ) + for path, value in self.values.items(): + generation = self.generations[path] + result = self.store.get(path) + assert isinstance(result, Found) + assert (bytes(result.value), result.generation) == (value, generation) + meta = self.store.head(path) + assert isinstance(meta, ObjectMetadata) + assert (meta.size, meta.generation) == (len(value), generation) + unchanged = self.store.get_if_changed(path, generation) + assert isinstance(unchanged, Unchanged) + assert unchanged.generation == generation + + def teardown(self) -> None: + if hasattr(self, "store"): + self.store.close() diff --git a/packages/zarr-storage/src/zarr_storage/experimental/testing/_suite.py b/packages/zarr-storage/src/zarr_storage/experimental/testing/_suite.py new file mode 100644 index 0000000000..31f9d4aacd --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/experimental/testing/_suite.py @@ -0,0 +1,1209 @@ +"""The storage contract, as tests. + +`StoreSuite` holds what every backend must do. Capabilities a backend may lack come as mixins: a +backend's test class combines `StoreSuite` with the mixin for each capability it has, or with the +mixin that checks it refuses that capability cleanly. Every test that takes the `store` fixture runs +twice, through `Store` and through `AsyncStore` (see `AsyncAPI`). + +Each behavior has one table-driven test for the expected outputs and one test per error case. +""" + +from __future__ import annotations + +import array +import asyncio +import pickle +import threading +import time +from collections import Counter +from dataclasses import dataclass +from functools import partial +from typing import TYPE_CHECKING, Literal + +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st +from hypothesis.stateful import run_state_machine_as_test + +from zarr_storage.experimental._errors import ( + BatchError, + InvalidByteRangeError, + InvalidKeyError, + KeyConflictError, + ReadOnlyError, + StoreClosedError, + UnsupportedOperationError, +) +from zarr_storage.experimental._types import ( + Copied, + Deleted, + Found, + Generation, + Key, + Missing, + ObjectMetadata, + OffsetRequest, + Prefix, + RangeRequest, + Rejected, + SuffixRequest, + Unchanged, + Written, +) +from zarr_storage.experimental.testing._api import ( + FullBackend, + StoreAPI, + async_api, + delete_if_match, + unwrap, +) +from zarr_storage.experimental.testing._stateful import Capabilities, StoreMachine + +if TYPE_CHECKING: + from collections.abc import Buffer, Callable, Iterable, Iterator + from pathlib import Path + + from zarr_storage.experimental._store import Store + from zarr_storage.experimental._types import ByteRange, ListItem + +__all__ = [ + "ConditionalDeleteSuite", + "ConditionalPutSuite", + "ConditionalRaceSuite", + "KeyAndDirectorySuite", + "KeyDirectoryConflictSuite", + "NoConditionalPutSuite", + "PickleSuite", + "StoreSuite", + "UniqueGenerationsSuite", +] + +VALUE = b"0123456789" + +# ---------------------------------------------------------------------------- tables + +VALID_KEYS = ["a", "a/b", "a/b/c", ".a", "a.b", "..a", "a..x", "__a", "zarr.json", "c/0/0", "a b"] +INVALID_KEYS = ["", "/", "/a", "a/", "a//b", ".", "..", "./a", "a/.", "a/../b", "a\x00b"] +INVALID_DIRECTORIES = ["//", "/a", "a//b", "..", "a/./b", "a\x00"] + +VALUES: list[tuple[str, Buffer, bytes]] = [ + ("bytes", VALUE, VALUE), + ("empty", b"", b""), + ("bytearray", bytearray(VALUE), VALUE), + ("memoryview", memoryview(VALUE), VALUE), + ("int-array", array.array("i", [1, 2]), array.array("i", [1, 2]).tobytes()), + ("2d-view", memoryview(VALUE).cast("B", (2, 5)), VALUE), +] + +BYTE_RANGES: list[tuple[ByteRange | None, bytes]] = [ + (None, VALUE), + (RangeRequest(0, 10), VALUE), + (RangeRequest(2, 5), b"234"), + (RangeRequest(5, 5), b""), + (RangeRequest(8, 100), b"89"), + (RangeRequest(10, 12), b""), + (OffsetRequest(0), VALUE), + (OffsetRequest(7), b"789"), + (OffsetRequest(10), b""), + (SuffixRequest(3), b"789"), + (SuffixRequest(0), b""), + (SuffixRequest(100), VALUE), +] + + +@dataclass(frozen=True) +class PutCase: + present: bool + operation: Literal["put", "put_if_absent", "put_if_match_current", "put_if_match_stale"] + outcome: type[Written | Rejected | Missing] + + +PUT_CASES = [ + PutCase(present=False, operation="put", outcome=Written), + PutCase(present=True, operation="put", outcome=Written), + PutCase(present=False, operation="put_if_absent", outcome=Written), + PutCase(present=True, operation="put_if_absent", outcome=Rejected), +] +PUT_IF_MATCH_CASES = [ + PutCase(present=True, operation="put_if_match_current", outcome=Written), + PutCase(present=True, operation="put_if_match_stale", outcome=Rejected), + PutCase(present=False, operation="put_if_match_stale", outcome=Missing), +] + + +@dataclass(frozen=True) +class DeleteCase: + present: bool + operation: Literal["delete", "delete_if_match_current", "delete_if_match_stale"] + outcome: type[Deleted | Rejected | Missing] + + +DELETE_CASES = [ + DeleteCase(present=False, operation="delete", outcome=Missing), + DeleteCase(present=True, operation="delete", outcome=Deleted), +] +DELETE_IF_MATCH_CASES = [ + DeleteCase(present=True, operation="delete_if_match_current", outcome=Deleted), + DeleteCase(present=True, operation="delete_if_match_stale", outcome=Rejected), + DeleteCase(present=False, operation="delete_if_match_stale", outcome=Missing), +] + + +@dataclass(frozen=True) +class IfChangedCase: + present: bool + generation: Literal["current", "stale"] + byte_range: ByteRange | None + outcome: type[Found | Missing | Unchanged] + expected: bytes | None = None + + +IF_CHANGED_CASES = [ + IfChangedCase(present=True, generation="current", byte_range=None, outcome=Unchanged), + IfChangedCase( + present=True, generation="current", byte_range=RangeRequest(2, 5), outcome=Unchanged + ), + IfChangedCase(present=True, generation="stale", byte_range=None, outcome=Found, expected=VALUE), + IfChangedCase( + present=True, + generation="stale", + byte_range=RangeRequest(2, 5), + outcome=Found, + expected=b"234", + ), + IfChangedCase(present=False, generation="stale", byte_range=None, outcome=Missing), +] + +BATCH_VALUES = {"a": VALUE, "b/c": b"xy"} + +GET_MANY_CASES: list[tuple[list[str | tuple[str, ByteRange | None]], list[bytes | None]]] = [ + ([], []), + (["a"], [VALUE]), + (["a", "b/c", "missing", "b"], [VALUE, b"xy", None, None]), + (["a", "a"], [VALUE, VALUE]), + ( + [("a", RangeRequest(2, 5)), ("a", SuffixRequest(2)), ("b/c", None), ("x", None)], + [b"234", b"89", b"xy", None], + ), +] +"""Requests to `get_many` over `BATCH_VALUES`, and what each reads (`None`: `Missing`).""" + + +TREE = [ + "zarr.json", + "a/zarr.json", + "a/c/0", + "a/c/1", + "ab/zarr.json", + "lat/zarr.json", + "lat_bnds/zarr.json", +] + + +def _without(*removed: str) -> set[str]: + return set(TREE) - set(removed) + + +DELETE_DIR_CASES: list[tuple[str, set[str]]] = [ + ("a", _without("a/zarr.json", "a/c/0", "a/c/1")), + ("a/", _without("a/zarr.json", "a/c/0", "a/c/1")), + ("lat", _without("lat/zarr.json")), + ("a/c", _without("a/c/0", "a/c/1")), + ("a/c/0", _without()), + ("missing", _without()), + ("", set()), +] + +LIST_DIRECTORIES = ["", "a", "a/", "a/c", "lat", "lat/", "missing", "a/c/0"] + +VIEW_ROOTS: list[tuple[list[str], str]] = [ + ([], ""), + ([""], ""), + (["a"], "a"), + (["a/"], "a"), + (["a", "b"], "a/b"), + (["a/b", ""], "a/b"), + (["a", "b/c/"], "a/b/c"), + (["/"], ""), + (["a", "/"], "a"), +] + +KEY_SETS = st.sets( + st.lists(st.sampled_from(["a", "b", "ab", "c.d", "_"]), min_size=1, max_size=3).map("/".join), + max_size=8, +) +LISTED_DIRECTORIES = st.sampled_from(["", "a", "b", "a/a", "ab", "a/b/"]) + + +def _model_list(keys: Iterable[str], directory: str) -> set[str]: + directory = directory.removesuffix("/") + if directory == "": + return set(keys) + return {k for k in keys if k.startswith(f"{directory}/")} + + +def _model_list_dir(keys: Iterable[str], directory: str) -> set[ListItem]: + directory = directory.removesuffix("/") + items: set[ListItem] = set() + for key in _model_list(keys, directory): + rest = key if directory == "" else key.removeprefix(f"{directory}/") + name, sep, _ = rest.partition("/") + items.add(Prefix(name) if sep else Key(name)) + return items + + +def _without_key_directories(keys: set[str]) -> set[str]: + """`keys` minus those that are also another key's directory.""" + return {k for k in keys if not any(other.startswith(f"{k}/") for other in keys)} + + +def _stale() -> Generation: + return Generation(object()) + + +# ---------------------------------------------------------------------------- operations + + +def _get_key(store: StoreAPI, key: str) -> object: + return store.get(key) + + +def _head_key(store: StoreAPI, key: str) -> object: + return store.head(key) + + +def _put_key(store: StoreAPI, key: str) -> object: + return store.put(key, VALUE) + + +def _delete_key(store: StoreAPI, key: str) -> object: + return store.delete(key) + + +KEY_OPERATIONS: list[Callable[[StoreAPI, str], object]] = [ + _get_key, + _head_key, + _put_key, + _delete_key, +] +KEY_OPERATION_IDS = ["get", "head", "put", "delete"] + + +def _view_of(store: StoreAPI, directory: str) -> object: + return store / directory + + +def _list_of(store: StoreAPI, directory: str) -> object: + return store.list(directory) + + +def _list_dir_of(store: StoreAPI, directory: str) -> object: + return store.list_dir(directory) + + +def _delete_dir_of(store: StoreAPI, directory: str) -> object: + store.delete_dir(directory) + return None + + +DIRECTORY_OPERATIONS: list[Callable[[StoreAPI, str], object]] = [ + _view_of, + _list_of, + _list_dir_of, + _delete_dir_of, +] +DIRECTORY_OPERATION_IDS = ["view", "list", "list_dir", "delete_dir"] + + +def _missing_get(store: StoreAPI) -> object: + return store.get("missing") + + +def _missing_get_directory(store: StoreAPI) -> object: + return store.get("a") + + +def _missing_get_range(store: StoreAPI) -> object: + return store.get("missing", byte_range=RangeRequest(0, 1)) + + +def _missing_get_ranges(store: StoreAPI) -> object: + return store.get_ranges("missing", [RangeRequest(0, 1)]) + + +def _missing_get_into(store: StoreAPI) -> object: + return store.get_into("missing", bytearray(1)) + + +def _missing_head(store: StoreAPI) -> object: + return store.head("a") + + +def _missing_get_if_changed(store: StoreAPI) -> object: + return store.get_if_changed("missing", _stale()) + + +def _missing_get_many(store: StoreAPI) -> object: + ((_, result),) = store.get_many(["missing"]) + return result + + +def _missing_get_into_many(store: StoreAPI) -> object: + ((_, result),) = store.get_into_many([("missing", bytearray(1))]) + return result + + +MISSING_READS: list[Callable[[StoreAPI], object]] = [ + _missing_get, + _missing_get_directory, + _missing_get_range, + _missing_get_if_changed, + _missing_get_ranges, + _missing_get_into, + _missing_get_many, + _missing_get_into_many, + _missing_head, +] +MISSING_READ_IDS = [ + "get", + "get-directory", + "get-range", + "get_if_changed", + "get_ranges", + "get_into", + "get_many", + "get_into_many", + "head", +] + + +def _put(store: StoreAPI) -> object: + return store.put("k", VALUE) + + +def _delete(store: StoreAPI) -> object: + return store.delete("k") + + +def _delete_dir(store: StoreAPI) -> object: + store.delete_dir("") + return None + + +def _put_many(store: StoreAPI) -> object: + return store.put_many([("k", VALUE)]) + + +def _delete_many(store: StoreAPI) -> object: + return store.delete_many(["k"]) + + +def _put_many_empty(store: StoreAPI) -> object: + return store.put_many([]) + + +WRITES: list[Callable[[StoreAPI], object]] = [ + _put, + _delete, + _delete_dir, + _put_many, + _delete_many, + _put_many_empty, +] +WRITE_IDS = ["put", "delete", "delete_dir", "put_many", "delete_many", "put_many-empty"] + + +def _get(store: StoreAPI) -> object: + return store.get("k") + + +def _get_ranges(store: StoreAPI) -> object: + return store.get_ranges("k", [SuffixRequest(1)]) + + +def _get_into(store: StoreAPI) -> object: + return store.get_into("k", bytearray(1)) + + +def _head(store: StoreAPI) -> object: + return store.head("k") + + +def _get_many(store: StoreAPI) -> object: + return store.get_many(["k"]) + + +def _get_into_many(store: StoreAPI) -> object: + return store.get_into_many([("k", bytearray(1))]) + + +def _list(store: StoreAPI) -> object: + return store.list() + + +def _list_dir(store: StoreAPI) -> object: + return store.list_dir() + + +CLOSED_OPERATIONS: list[Callable[[StoreAPI], object]] = [ + _get, + _get_ranges, + _get_into, + _head, + _put, + _delete, + _delete_dir, + _get_many, + _get_into_many, + _put_many, + _delete_many, + _list, + _list_dir, +] +CLOSED_IDS = [ + "get", + "get_ranges", + "get_into", + "head", + "put", + "delete", + "delete_dir", + "get_many", + "get_into_many", + "put_many", + "delete_many", + "list", + "list_dir", +] + + +def _get_many_invalid(store: StoreAPI) -> object: + return store.get_many(["x", "/bad"]) + + +def _get_into_many_invalid(store: StoreAPI) -> object: + return store.get_into_many([("x", bytearray(1)), ("/bad", bytearray(1))]) + + +def _put_many_invalid(store: StoreAPI) -> object: + return store.put_many([("y", VALUE), ("/bad", VALUE)]) + + +def _delete_many_invalid(store: StoreAPI) -> object: + return store.delete_many(["x", "/bad"]) + + +INVALID_BATCHES: list[Callable[[StoreAPI], object]] = [ + _get_many_invalid, + _get_into_many_invalid, + _put_many_invalid, + _delete_many_invalid, +] +INVALID_BATCH_IDS = ["get_many", "get_into_many", "put_many", "delete_many"] + + +def _put_many_twice(store: StoreAPI) -> object: + return store.put_many([("x", b"1"), ("y", b"2"), ("x", b"3")]) + + +def _delete_many_twice(store: StoreAPI) -> object: + return store.delete_many(["x", "x"]) + + +def _write_repeatedly( + store: Store[FullBackend], stop: threading.Event, written: dict[Generation, int] +) -> None: + fill = 0 + while not stop.is_set(): + fill = (fill + 1) % 256 + written[store.put("k", bytes([fill]) * 1000).generation] = fill + + +def _create( + store: Store[FullBackend], key: str, barrier: threading.Barrier, results: list[bool] +) -> None: + barrier.wait() + results.append(isinstance(store.put_if_absent(key, VALUE), Written)) + + +def _check_put(store: StoreAPI, case: PutCase) -> None: + current = store.put("k", VALUE).generation if case.present else None + match case.operation: + case "put": + result = store.put("k", b"new") + case "put_if_absent": + result = store.put_if_absent("k", b"new") + case "put_if_match_current": + assert current is not None + result = store.put_if_match("k", b"new", current) + case "put_if_match_stale": + result = store.put_if_match("k", b"new", _stale()) + assert isinstance(result, case.outcome) + stored = store.get("k") + match result: + case Written(generation=generation): + assert generation != current + assert isinstance(stored, Found) + assert (bytes(stored.value), stored.generation) == (b"new", generation) + case Rejected(generation=generation): + assert generation == current + assert isinstance(stored, Found) + assert bytes(stored.value) == VALUE + case Missing(): + assert isinstance(stored, Missing) + + +def _check_delete(store: StoreAPI, case: DeleteCase) -> None: + current = store.put("k", VALUE).generation if case.present else None + match case.operation: + case "delete": + result = store.delete("k") + case "delete_if_match_current": + assert current is not None + result = delete_if_match(store, "k", current) + case "delete_if_match_stale": + result = delete_if_match(store, "k", _stale()) + assert isinstance(result, case.outcome) + match result: + case Deleted(generation=generation) | Rejected(generation=generation): + assert generation == current + case Missing(): + pass + assert store.exists("k") is isinstance(result, Rejected) + + +def _check_listing(store: Store[FullBackend], keys: set[str], directory: str) -> None: + for key in keys: + store.put(key, VALUE) + assert set(store.list(directory)) == _model_list(keys, directory) + assert set(store.list_dir(directory)) == _model_list_dir(keys, directory) + + +def _machine_store( + suite: StoreSuite, + directories: pytest.TempPathFactory, + api: Literal["sync", "async"], + runner: asyncio.Runner, +) -> StoreAPI: + store = suite.make_store(directories.mktemp("machine")) + return store if api == "sync" else async_api(store, runner) + + +# ---------------------------------------------------------------------------- the core suite + + +class StoreSuite: + """What every backend must do. + + Override `make_store` to return an empty, writable store over a fresh backend. `directory` is a + new empty directory a filesystem backend can use; other backends ignore it. + """ + + def make_store(self, directory: Path) -> Store[FullBackend]: + raise NotImplementedError("Override make_store to return an empty store.") + + @pytest.fixture(params=["sync", "async"]) + def store(self, request: pytest.FixtureRequest, tmp_path: Path) -> Iterator[StoreAPI]: + store = self.make_store(tmp_path) + if request.param == "sync": + yield store + return + with asyncio.Runner() as runner: + yield async_api(store, runner) + + # ------------------------------------------------------------------ everything at once + + @pytest.mark.parametrize("api", ["sync", "async"]) + def test_state_machine( + self, tmp_path_factory: pytest.TempPathFactory, api: Literal["sync", "async"] + ) -> None: + """Random sequences of operations through random views agree with a dict model.""" + capabilities = Capabilities( + conditional_put=isinstance(self, ConditionalPutSuite), + conditional_delete=isinstance(self, ConditionalDeleteSuite), + holds_key_and_directory=isinstance(self, KeyAndDirectorySuite), + leaves_empty_directories=isinstance(self, KeyDirectoryConflictSuite), + unique_generations=isinstance(self, UniqueGenerationsSuite), + ) + with asyncio.Runner() as runner: + make_store = partial(_machine_store, self, tmp_path_factory, api, runner) + run_state_machine_as_test( + # Hypothesis calls the factory with no arguments; a partial is a fine factory. + partial(StoreMachine, make_store, capabilities), # pyright: ignore[reportArgumentType] + settings=settings( + max_examples=40, + stateful_step_count=30, + deadline=None, + suppress_health_check=[HealthCheck.differing_executors], + ), + ) + + # ------------------------------------------------------------------ keys + + @pytest.mark.parametrize("key", VALID_KEYS) + def test_valid_key_round_trips(self, store: StoreAPI, key: str) -> None: + store.put(key, VALUE) + result = store.get(key) + assert isinstance(result, Found) + assert bytes(result.value) == VALUE + assert key in set(store.list()) + + @pytest.mark.parametrize("key", INVALID_KEYS) + @pytest.mark.parametrize("operation", KEY_OPERATIONS, ids=KEY_OPERATION_IDS) + def test_invalid_key_raises( + self, store: StoreAPI, key: str, operation: Callable[[StoreAPI, str], object] + ) -> None: + with pytest.raises(InvalidKeyError): + operation(store, key) + + @pytest.mark.parametrize("directory", INVALID_DIRECTORIES) + @pytest.mark.parametrize("operation", DIRECTORY_OPERATIONS, ids=DIRECTORY_OPERATION_IDS) + def test_invalid_directory_raises( + self, store: StoreAPI, directory: str, operation: Callable[[StoreAPI, str], object] + ) -> None: + with pytest.raises(InvalidKeyError): + operation(store, directory) + + # ------------------------------------------------------------------ get / put + + @pytest.mark.parametrize( + ("value", "expected"), [v[1:] for v in VALUES], ids=[v[0] for v in VALUES] + ) + def test_put_then_get(self, store: StoreAPI, value: Buffer, expected: bytes) -> None: + written = store.put("k", value) + result = store.get("k") + assert isinstance(result, Found) + assert (bytes(result.value), result.generation) == (expected, written.generation) + assert result.read_at is None or abs(result.read_at - time.time()) < 3600 + meta = store.head("k") + assert isinstance(meta, ObjectMetadata) + assert (meta.size, meta.generation) == (len(expected), written.generation) + assert meta.last_modified is None or abs(meta.last_modified - time.time()) < 3600 + assert store.exists("k") + + def test_put_copies_the_value(self, store: StoreAPI) -> None: + value = bytearray(VALUE) + store.put("k", value) + value[0:1] = b"X" + result = store.get("k") + assert isinstance(result, Found) + assert bytes(result.value) == VALUE + + @pytest.mark.parametrize("read", MISSING_READS, ids=MISSING_READ_IDS) + def test_reads_of_missing_key( + self, store: StoreAPI, read: Callable[[StoreAPI], object] + ) -> None: + store.put("a/k", VALUE) + assert isinstance(read(store), Missing) + assert not store.exists("a") + + @pytest.mark.parametrize("case", IF_CHANGED_CASES, ids=repr) + def test_get_if_changed(self, store: StoreAPI, case: IfChangedCase) -> None: + current = store.put("k", VALUE).generation if case.present else None + generation = current if case.generation == "current" and current is not None else _stale() + result = store.get_if_changed("k", generation, byte_range=case.byte_range) + assert isinstance(result, case.outcome) + match result: + case Unchanged(): + assert result.generation == current + case Found(): + assert (bytes(result.value), result.generation) == (case.expected, current) + case Missing(): + pass + + # ------------------------------------------------------------------ byte ranges + + @pytest.mark.parametrize(("byte_range", "expected"), BYTE_RANGES) + def test_byte_range( + self, store: StoreAPI, byte_range: ByteRange | None, expected: bytes + ) -> None: + store.put("k", VALUE) + result = store.get("k", byte_range=byte_range) + assert isinstance(result, Found) + assert bytes(result.value) == expected + out = bytearray(len(VALUE) + 1) + copied = store.get_into("k", out, byte_range=byte_range) + assert isinstance(copied, Copied) + assert (copied.size, copied.generation) == (len(expected), result.generation) + assert bytes(out[: copied.size]) == expected + if byte_range is not None: + ranges = store.get_ranges("k", [byte_range, SuffixRequest(1)]) + assert not isinstance(ranges, Missing) + assert [bytes(v) for v in ranges.values] == [expected, b"9"] + assert ranges.generation == result.generation + + @pytest.mark.parametrize("byte_range", [RangeRequest(11, 12), OffsetRequest(11)]) + def test_byte_range_past_end_raises(self, store: StoreAPI, byte_range: ByteRange) -> None: + store.put("k", VALUE) + with pytest.raises(InvalidByteRangeError): + store.get("k", byte_range=byte_range) + + def test_get_into_short_buffer_raises(self, store: StoreAPI) -> None: + store.put("k", VALUE) + with pytest.raises(ValueError, match="holds"): + store.get_into("k", bytearray(len(VALUE) - 1)) + + def test_get_into_read_only_buffer_raises(self, store: StoreAPI) -> None: + store.put("k", VALUE) + with pytest.raises(ValueError, match="writable"): + store.get_into("k", memoryview(bytes(len(VALUE)))) + + def test_get_into_non_contiguous_buffer_raises(self, store: StoreAPI) -> None: + store.put("k", VALUE) + with pytest.raises(ValueError, match="contiguous"): + store.get_into("k", memoryview(bytearray(2 * len(VALUE)))[::2]) + + @pytest.mark.parametrize("api", ["sync", "async"]) + def test_get_ranges_reads_one_generation(self, tmp_path: Path, api: str) -> None: + """Ranges read while another thread rewrites the value all come from the write whose + generation the result reports.""" + store = self.make_store(tmp_path) + written: dict[Generation, int] = {} + written[store.put("k", bytes(1000)).generation] = 0 + stop = threading.Event() + writer = threading.Thread(target=_write_repeatedly, args=(store, stop, written)) + seen: list[tuple[Generation, bytes, bytes]] = [] + writer.start() + try: + with asyncio.Runner() as runner: + reader: StoreAPI = store if api == "sync" else async_api(store, runner) + for _ in range(200): + result = reader.get_ranges("k", [RangeRequest(0, 1), SuffixRequest(1)]) + assert not isinstance(result, Missing) + first, last = (bytes(v) for v in result.values) + seen.append((result.generation, first, last)) + finally: + stop.set() + writer.join() + for generation, first, last in seen: + assert first == last + if isinstance(self, UniqueGenerationsSuite): + assert first == bytes([written[generation]]) + + # ------------------------------------------------------------------ writes + + @pytest.mark.parametrize("case", PUT_CASES, ids=repr) + def test_put(self, store: StoreAPI, case: PutCase) -> None: + _check_put(store, case) + + def test_concurrent_creates_apply_once(self, tmp_path: Path) -> None: + """Of many racing `put_if_absent` writes to one key, exactly one applies.""" + store = self.make_store(tmp_path) + for round_ in range(20): + barrier = threading.Barrier(8) + results: list[bool] = [] + threads = [ + threading.Thread(target=_create, args=(store, f"k{round_}", barrier, results)) + for _ in range(8) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert results.count(True) == 1 + + @pytest.mark.parametrize("case", DELETE_CASES, ids=repr) + def test_delete(self, store: StoreAPI, case: DeleteCase) -> None: + _check_delete(store, case) + + def test_delete_of_a_directory_deletes_nothing(self, store: StoreAPI) -> None: + store.put("a/b", VALUE) + assert isinstance(store.delete("a"), Missing) + assert store.exists("a/b") + + @pytest.mark.parametrize(("directory", "remaining"), DELETE_DIR_CASES) + def test_delete_dir(self, store: StoreAPI, directory: str, remaining: set[str]) -> None: + for key in TREE: + store.put(key, VALUE) + store.delete_dir(directory) + assert set(store.list()) == remaining + + # ------------------------------------------------------------------ batches + + @pytest.mark.parametrize(("requests", "expected"), GET_MANY_CASES) + def test_get_many( + self, + store: StoreAPI, + requests: list[str | tuple[str, ByteRange | None]], + expected: list[bytes | None], + ) -> None: + written = dict(store.put_many(BATCH_VALUES.items())) + read: Counter[tuple[object, bytes | None]] = Counter() + for request, result in store.get_many(requests): + key = request if isinstance(request, str) else request[0] + match result: + case Found(value=value, generation=generation): + assert generation == written[key].generation + read[request, bytes(value)] += 1 + case Missing(): + read[request, None] += 1 + assert read == Counter(zip(requests, expected, strict=True)) + + def test_get_into_many(self, store: StoreAPI) -> None: + written = dict(store.put_many(BATCH_VALUES.items())) + whole, part, absent = bytearray(len(VALUE)), bytearray(2), bytearray(1) + results = { + request[0]: result + for request, result in store.get_into_many( + [("a", whole), ("b/c", part, OffsetRequest(1)), ("missing", absent)] + ) + } + assert results["a"] == Copied(len(VALUE), written["a"].generation, results["a"].read_at) + assert results["b/c"] == Copied(1, written["b/c"].generation, results["b/c"].read_at) + assert isinstance(results["missing"], Missing) + assert (bytes(whole), bytes(part), bytes(absent)) == (VALUE, b"y\x00", b"\x00") + + def test_put_many_and_delete_many(self, store: StoreAPI) -> None: + store.put("b/c", b"old") + items = [("b/c", b"xy"), ("a", VALUE), ("d", b"")] + written = store.put_many(items) + assert [key for key, _ in written] == ["b/c", "a", "d"] + for (key, value), (_, result) in zip(items, written, strict=True): + stored = store.get(key) + assert isinstance(stored, Found) + assert (bytes(stored.value), stored.generation) == (value, result.generation) + deleted = store.delete_many(["a", "missing", "b/c"]) + assert [(key, type(result)) for key, result in deleted] == [ + ("a", Deleted), + ("missing", Missing), + ("b/c", Deleted), + ] + assert deleted[0][1] == Deleted(written[1][1].generation) + assert set(store.list()) == {"d"} + assert store.put_many([]) == [] + assert store.delete_many([]) == [] + + def test_get_many_taken_in_part(self, store: StoreAPI) -> None: + """A caller may stop taking results; the store stays usable.""" + store.put_many([(f"k{i}", VALUE) for i in range(40)]) + results = store.get_many(f"k{i}" for i in range(40)) + assert isinstance(next(iter(results))[1], Found) + del results + assert len(list(store.get_many(f"k{i}" for i in range(40)))) == 40 + + def test_batches_through_a_view(self, store: StoreAPI) -> None: + view = store / "r" + view.put_many([("k", VALUE)]) + assert set(store.list()) == {"r/k"} + assert [key for key, _ in (store / "r").get_many(["k"])] == ["k"] + assert view.delete_many(["k"])[0][1] != Missing() + assert set(store.list()) == set() + + @pytest.mark.parametrize("batch", INVALID_BATCHES, ids=INVALID_BATCH_IDS) + def test_batch_with_an_invalid_key_raises_before_any_operation( + self, store: StoreAPI, batch: Callable[[StoreAPI], object] + ) -> None: + store.put("x", VALUE) + with pytest.raises(InvalidKeyError): + batch(store) + assert set(store.list()) == {"x"} + + @pytest.mark.parametrize("batch", [_put_many_twice, _delete_many_twice], ids=["put", "delete"]) + def test_write_batch_naming_a_key_twice_raises( + self, store: StoreAPI, batch: Callable[[StoreAPI], object] + ) -> None: + store.put("x", VALUE) + with pytest.raises(ValueError, match="more than once"): + batch(store) + assert set(store.list()) == {"x"} + result = store.get("x") + assert isinstance(result, Found) + assert bytes(result.value) == VALUE + + # ------------------------------------------------------------------ listing + + @pytest.mark.parametrize("directory", LIST_DIRECTORIES) + def test_list(self, store: StoreAPI, directory: str) -> None: + for key in TREE: + store.put(key, VALUE) + listed, children = list(store.list(directory)), list(store.list_dir(directory)) + assert len(listed) == len(set(listed)) + assert len(children) == len(set(children)) + assert set(listed) == _model_list(TREE, directory) + assert set(children) == _model_list_dir(TREE, directory) + + @given(keys=KEY_SETS, directory=LISTED_DIRECTORIES) + # Each backend's subclass runs this test; that is the point of the suite, not a flaky executor. + @settings( + max_examples=50, deadline=None, suppress_health_check=[HealthCheck.differing_executors] + ) + def test_listing_matches_a_model( + self, tmp_path_factory: pytest.TempPathFactory, keys: set[str], directory: str + ) -> None: + store = self.make_store(tmp_path_factory.mktemp("store")) + _check_listing(store, _without_key_directories(keys), directory) + + # ------------------------------------------------------------------ views + + @pytest.mark.parametrize(("path", "root"), VIEW_ROOTS) + def test_view_root(self, store: StoreAPI, path: list[str], root: str) -> None: + view = store + for directory in path: + view = view / directory + assert view.root == root + + def test_views_share_the_backend(self, store: StoreAPI) -> None: + child = store / "a" + child.put("k", VALUE) + assert store.exists("a/k") + store.put("a/b/c", VALUE) + assert set(child.list()) == {"k", "b/c"} + assert set(child.list("b")) == {"b/c"} + assert set(child.list_dir()) == {Key("k"), Prefix("b")} + result = child.get_ranges("b/c", [SuffixRequest(1)]) + assert not isinstance(result, Missing) + assert [bytes(v) for v in result.values] == [b"9"] + meta = child.head("b/c") + assert isinstance(meta, ObjectMetadata) + assert meta.size == len(VALUE) + assert set((store / "lat").list()) == set() + child.delete_dir() + assert set(store.list()) == set() + + def test_identity(self, store: StoreAPI, tmp_path_factory: pytest.TempPathFactory) -> None: + other = self.make_store(tmp_path_factory.mktemp("other")) + base = unwrap(store) + a, ab, lat, lat_bnds = base / "a", base / "a/b", base / "lat", base / "lat_bnds" + table = [ + (base, base / "", True, True), + (a, ab, True, True), + (ab, a, True, True), + (base, lat, True, True), + (lat, lat_bnds, True, False), + (a, lat, True, False), + (a, a.as_read_only(), True, True), + (base, other, False, False), + (a, other / "a", False, False), + ] + for left, right, shares, overlaps in table: + assert left.shares_backend(right) is shares + assert left.overlaps(right) is overlaps + assert base != base / "" + + def test_read_only_views(self, store: StoreAPI) -> None: + store.put("k", VALUE) + reader = store.as_read_only() + assert (store.read_only, reader.read_only, (reader / "x").read_only) == (False, True, True) + assert reader.as_read_only().read_only + assert reader.exists("k") + + @pytest.mark.parametrize("write", WRITES, ids=WRITE_IDS) + def test_write_through_read_only_view_raises( + self, store: StoreAPI, write: Callable[[StoreAPI], object] + ) -> None: + store.put("k", VALUE) + with pytest.raises(ReadOnlyError): + write(store.as_read_only()) + assert store.exists("k") + + # ------------------------------------------------------------------ lifecycle + + def test_closing_a_derived_view_leaves_the_backend_open(self, store: StoreAPI) -> None: + store.put("k", VALUE) + (store / "a").close() + store.as_read_only().close() + assert not store.closed + assert store.exists("k") + + @pytest.mark.parametrize("operation", CLOSED_OPERATIONS, ids=CLOSED_IDS) + def test_use_after_owner_closes_raises( + self, store: StoreAPI, operation: Callable[[StoreAPI], object] + ) -> None: + view = store / "a" + with store: + store.put("a/k", VALUE) + assert view.closed + with pytest.raises(StoreClosedError): + operation(view) + + @pytest.mark.parametrize("listing", ["list", "list_dir", "get_many", "get_into_many"]) + def test_iterating_after_close_raises(self, store: StoreAPI, listing: str) -> None: + store.put("a", VALUE) + store.put("b", VALUE) + items = { + "list": partial(store.list), + "list_dir": partial(store.list_dir), + "get_many": partial(store.get_many, ["a", "b"]), + "get_into_many": partial(store.get_into_many, [("a", bytearray(len(VALUE)))]), + }[listing]() + store.close() + with pytest.raises(StoreClosedError): + next(iter(items)) + + +# ---------------------------------------------------------------------------- capability mixins + + +class UniqueGenerationsSuite: + """For backends that never hand out a generation twice, even after a delete. + + obstore's `LocalStore` doesn't qualify: its ETag comes from the inode and mtime, which a + filesystem such as ext4 can repeat. + """ + + def make_store(self, directory: Path) -> Store[FullBackend]: + raise NotImplementedError("Override make_store to return an empty store.") + + def test_rewrite_changes_generation(self, store: StoreAPI) -> None: + generations = [store.put("k", value).generation for value in [VALUE, VALUE, b"x" * 10]] + assert len(set(generations)) == 3 + + def test_generations_are_not_reused_after_deletes(self, tmp_path: Path) -> None: + store = self.make_store(tmp_path) + seen: set[Generation] = set() + for i in range(200): + generation = store.put(f"k{i % 3}", VALUE).generation + assert generation not in seen + seen.add(generation) + store.delete(f"k{(i + 1) % 3}") + + +class ConditionalPutSuite: + """For backends whose `put_if_match` works.""" + + @pytest.mark.parametrize("case", PUT_IF_MATCH_CASES, ids=repr) + def test_put_if_match(self, store: StoreAPI, case: PutCase) -> None: + _check_put(store, case) + + +class NoConditionalPutSuite: + """For backends whose `put_if_match` raises, because the store underneath can't do it.""" + + def test_put_if_match_raises(self, store: StoreAPI) -> None: + current = store.put("k", VALUE).generation + with pytest.raises(UnsupportedOperationError): + store.put_if_match("k", b"new", current) + + +class ConditionalDeleteSuite: + """For backends with `delete_if_match` (`DeletableIfMatch`).""" + + @pytest.mark.parametrize("case", DELETE_IF_MATCH_CASES, ids=repr) + def test_delete_if_match(self, store: StoreAPI, case: DeleteCase) -> None: + _check_delete(store, case) + + +def _race_put( + store: Store[FullBackend], + generation: Generation, + barrier: threading.Barrier, + results: list[str], +) -> None: + barrier.wait() + if isinstance(store.put_if_match("d/k", b"new", generation), Written): + results.append("put") + + +def _race_delete( + store: Store[FullBackend], + generation: Generation, + barrier: threading.Barrier, + results: list[str], +) -> None: + barrier.wait() + if isinstance(delete_if_match(store, "d/k", generation), Deleted): + results.append("delete") + + +class ConditionalRaceSuite: + """For backends with conditional puts and deletes: racing ones from one generation apply once.""" + + def make_store(self, directory: Path) -> Store[FullBackend]: + raise NotImplementedError("Override make_store to return an empty store.") + + def test_conditional_put_and_delete_apply_once(self, tmp_path: Path) -> None: + store = self.make_store(tmp_path) + for _ in range(100): + generation = store.put("d/k", VALUE).generation + barrier = threading.Barrier(4) + results: list[str] = [] + threads = [ + threading.Thread(target=target, args=(store, generation, barrier, results)) + for target in (_race_put, _race_delete, _race_put, _race_delete) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert len(results) == 1 + + +class KeyAndDirectorySuite: + """For backends that hold a key `a` and a key `a/b` at once (object stores, memory).""" + + def make_store(self, directory: Path) -> Store[FullBackend]: + raise NotImplementedError("Override make_store to return an empty store.") + + def test_list_dir_reports_a_name_that_is_both_key_and_prefix(self, store: StoreAPI) -> None: + store.put("a/b", VALUE) + store.put("a", VALUE) + assert set(store.list_dir()) == {Key("a"), Prefix("a")} + assert set(store.list()) == {"a", "a/b"} + + def test_delete_dir_keeps_a_key_with_the_directory_name(self, store: StoreAPI) -> None: + store.put("a", VALUE) + store.put("a/b", VALUE) + store.delete_dir("a") + assert set(store.list()) == {"a"} + + @given(keys=KEY_SETS, directory=LISTED_DIRECTORIES) + @settings( + max_examples=50, deadline=None, suppress_health_check=[HealthCheck.differing_executors] + ) + def test_listing_with_key_directories_matches_a_model( + self, tmp_path_factory: pytest.TempPathFactory, keys: set[str], directory: str + ) -> None: + _check_listing(self.make_store(tmp_path_factory.mktemp("store")), keys, directory) + + +class KeyDirectoryConflictSuite: + """For backends that can't hold a key and a directory with one name (filesystems).""" + + def test_key_over_a_directory_raises(self, store: StoreAPI) -> None: + store.put("a/b", VALUE) + with pytest.raises(KeyConflictError): + store.put("a", VALUE) + + def test_directory_under_a_key_raises(self, store: StoreAPI) -> None: + store.put("a", VALUE) + with pytest.raises(KeyConflictError): + store.put("a/b", VALUE) + + def test_put_many_with_a_conflict_raises_batch_error(self, store: StoreAPI) -> None: + with pytest.raises(BatchError) as caught: + store.put_many([("a", VALUE), ("a/b", VALUE)]) + error = caught.value + assert [type(e) for e in error.exceptions] == [KeyConflictError] + ((key, result),) = error.completed + assert isinstance(result, Written) + assert error.remaining == (({"a", "a/b"} - {key}).pop(),) + assert set(store.list()) == {key} + + def test_reads_under_a_key_find_nothing(self, store: StoreAPI) -> None: + store.put("a", VALUE) + assert isinstance(store.get("a/b"), Missing) + assert isinstance(store.get_if_changed("a/b", _stale()), Missing) + assert isinstance(store.get_into("a/b", bytearray(len(VALUE))), Missing) + assert isinstance(store.head("a/b"), Missing) + assert not store.exists("a/b") + assert isinstance(store.get_ranges("a/b", [SuffixRequest(1)]), Missing) + assert isinstance(store.delete("a/b"), Missing) + assert set(store.list("a")) == set() + assert set(store.list_dir("a")) == set() + assert set(store.list_dir("a/b")) == set() + + +class PickleSuite: + """For backends whose stores can be pickled.""" + + @pytest.mark.parametrize(("root", "read_only"), [("", False), ("a", True), ("a/b", False)]) + def test_pickle_round_trip(self, store: StoreAPI, root: str, read_only: bool) -> None: + store.put("a/b/k", VALUE) + view = unwrap((store / root).as_read_only() if read_only else store / root) + restored = pickle.loads(pickle.dumps(view)) + assert (restored.root, restored.read_only, restored.closed) == (root, read_only, False) + assert set(restored.list()) == set(view.list()) + + def test_pickle_keeps_closed(self, store: StoreAPI) -> None: + store.close() + assert pickle.loads(pickle.dumps(unwrap(store))).closed diff --git a/packages/zarr-storage/tests/__init__.py b/packages/zarr-storage/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-storage/tests/experimental/__init__.py b/packages/zarr-storage/tests/experimental/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-storage/tests/experimental/test_batch.py b/packages/zarr-storage/tests/experimental/test_batch.py new file mode 100644 index 0000000000..100d06a4c1 --- /dev/null +++ b/packages/zarr-storage/tests/experimental/test_batch.py @@ -0,0 +1,119 @@ +"""The runners behind every batch: windows, ordering and the failure rule.""" + +from __future__ import annotations + +import asyncio +import threading +import time +from typing import TYPE_CHECKING + +import pytest + +from zarr_storage.experimental import BatchError +from zarr_storage.experimental._batch import run_many, run_many_async +from zarr_storage.experimental._resources import ThreadPool + +if TYPE_CHECKING: + from collections.abc import AsyncIterator + + +class _Tracker: + """Squares its argument, recording what started and the most calls ever running at once.""" + + def __init__(self, fails: int | None = None) -> None: + self._fails = fails + self._lock = threading.Lock() + self._running = 0 + self.most = 0 + self.started: set[int] = set() + + def _enter(self, x: int) -> None: + with self._lock: + self.started.add(x) + self._running += 1 + self.most = max(self.most, self._running) + + def _exit(self) -> None: + with self._lock: + self._running -= 1 + + def __call__(self, x: int) -> int: + self._enter(x) + try: + if x == self._fails: + raise ValueError(x) + time.sleep(0.01) + return x * x + finally: + self._exit() + + async def call_async(self, x: int) -> int: + self._enter(x) + try: + if x == self._fails: + raise ValueError(x) + await asyncio.sleep(0.01) + return x * x + finally: + self._exit() + + +def _run(tracker: _Tracker, mode: str, window: int, n: int, into: list[tuple[int, int]]) -> None: + """Run `tracker` over `range(n)`, appending each result to `into` as it is yielded.""" + requests = [(x,) for x in range(n)] + if mode == "serial": + into.extend(run_many(tracker, requests)) + elif mode == "threads": + pool = ThreadPool(8) + try: + into.extend(run_many(tracker, requests, pool, window)) + finally: + pool.shutdown() + else: + asyncio.run(_collect(run_many_async(tracker.call_async, requests, window), into)) + + +async def _collect(results: AsyncIterator[tuple[int, int]], into: list[tuple[int, int]]) -> None: + async for pair in results: + into.append(pair) # noqa: PERF401 -- a failure keeps the pairs before it + + +@pytest.mark.parametrize( + ("mode", "window"), + [("serial", 1), ("threads", 1), ("threads", 3), ("async", 1), ("async", 3)], +) +@pytest.mark.parametrize("n", [0, 1, 7]) +def test_runner(mode: str, window: int, n: int) -> None: + """Every request runs once, its result keyed by its index, never more than `window` at once.""" + tracker = _Tracker() + results: list[tuple[int, int]] = [] + _run(tracker, mode, window, n, results) + assert sorted(results) == [(x, x * x) for x in range(n)] + assert tracker.most <= window + + +@pytest.mark.parametrize(("mode", "window"), [("serial", 1), ("threads", 3), ("async", 3)]) +def test_runner_stops_starting_after_a_failure(mode: str, window: int) -> None: + """The failure's peers already running finish and are yielded; nothing new starts. + + On a pool, peers still queued when the failure comes are cancelled, so at most the first + window started. + """ + tracker = _Tracker(fails=0) + results: list[tuple[int, int]] = [] + with pytest.raises(ExceptionGroup) as caught: + _run(tracker, mode, window, 10, results) + assert [type(e) for e in caught.value.exceptions] == [ValueError] + assert 0 in tracker.started + assert tracker.started <= set(range(window)) + assert sorted(results) == [(x, x * x) for x in sorted(tracker.started - {0})] + + +def test_batch_error_keeps_its_report_when_split() -> None: + """`except*` splits a group; each part is still a `BatchError` with the batch's report.""" + error = BatchError("x", [ValueError(), KeyError()], completed=(("a", 1),), remaining=("b",)) + values, rest = error.split(ValueError) + for part, kind in [(values, ValueError), (rest, KeyError)]: + assert isinstance(part, BatchError) + assert [type(e) for e in part.exceptions] == [kind] + assert (part.completed, part.remaining) == ((("a", 1),), ("b",)) diff --git a/packages/zarr-storage/tests/experimental/test_local.py b/packages/zarr-storage/tests/experimental/test_local.py new file mode 100644 index 0000000000..a3c68da3a3 --- /dev/null +++ b/packages/zarr-storage/tests/experimental/test_local.py @@ -0,0 +1,549 @@ +from __future__ import annotations + +import errno +import multiprocessing +import os +import shutil +import threading +import time +from functools import partial +from typing import TYPE_CHECKING + +import pytest +from obstore.store import LocalStore + +from zarr_storage.experimental import ( + Found, + Generation, + InvalidKeyError, + Key, + KeyConflictError, + Missing, + Prefix, + Rejected, + Store, + UnsupportedOperationError, + Written, +) +from zarr_storage.experimental.backends import LocalBackend, ObjectStoreBackend, _local +from zarr_storage.experimental.backends._local import ( + RESERVED_SUFFIX, + _directory_lock, + segment_problem, +) +from zarr_storage.experimental.testing import ( + ConditionalDeleteSuite, + ConditionalPutSuite, + ConditionalRaceSuite, + KeyDirectoryConflictSuite, + PickleSuite, + StoreSuite, + UniqueGenerationsSuite, +) + +if TYPE_CHECKING: + from collections.abc import Callable + from pathlib import Path + + +class TestLocalBackend( + StoreSuite, + UniqueGenerationsSuite, + ConditionalPutSuite, + ConditionalDeleteSuite, + ConditionalRaceSuite, + KeyDirectoryConflictSuite, + PickleSuite, +): + def make_store(self, directory: Path) -> Store[LocalBackend]: + return Store(LocalBackend(directory)) + + +def test_listing_skips_backend_files(tmp_path: Path) -> None: + """Lock files and temporary files are never listed.""" + store = Store(LocalBackend(tmp_path)) + store.put("a/k", b"x") + (tmp_path / "a" / f"k.123{RESERVED_SUFFIX}").write_bytes(b"partial") + assert (tmp_path / "a" / f"lock{RESERVED_SUFFIX}").exists() + assert set(store.list()) == {"a/k"} + assert set(store.list_dir("a")) == {Key("k")} + + +def test_delete_leaves_the_directory(tmp_path: Path) -> None: + """Deleting a key leaves its directory, which `list_dir` reports as an empty `Prefix`.""" + store = Store(LocalBackend(tmp_path)) + store.put("a/b/c", b"x") + store.delete("a/b/c") + assert set(store.list()) == set() + assert set(store.list_dir("a")) == {Prefix("b")} + + +def test_failed_put_leaves_no_staged_files(tmp_path: Path) -> None: + store = Store(LocalBackend(tmp_path)) + store.put("k", b"x") + assert isinstance(store.put_if_absent("k", b"y"), Rejected) + assert list((tmp_path / f"staging{RESERVED_SUFFIX}").iterdir()) == [] + + +def _disk_full(*_: object) -> None: + raise OSError(errno.ENOSPC, "No space left on device") + + +def test_put_that_fails_while_staging_leaves_no_staged_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A write that fails part way (a full disk) must not leave its partial file behind.""" + store = Store(LocalBackend(tmp_path)) + monkeypatch.setattr("zarr_storage.experimental.backends._local._set_mtime", _disk_full) + with pytest.raises(OSError, match="No space"): + store.put("k", b"x") + assert list((tmp_path / f"staging{RESERVED_SUFFIX}").iterdir()) == [] + + +def test_delete_dir_of_the_root_keeps_backend_files(tmp_path: Path) -> None: + store = Store(LocalBackend(tmp_path)) + store.put("k", b"x") + store.delete_dir("") + assert {p.name for p in tmp_path.iterdir()} == { + f"lock{RESERVED_SUFFIX}", + f"staging{RESERVED_SUFFIX}", + } + assert isinstance(store.put_if_absent("k", b"y"), Written) + + +def test_put_recreates_a_removed_root(tmp_path: Path) -> None: + """An outer backend can remove a nested backend's root; the nested one recreates it.""" + outer = Store(LocalBackend(tmp_path)) + inner = Store(LocalBackend.create(tmp_path / "sub")) + outer.delete_dir("sub") + inner.put("k", b"x") + assert outer.exists("sub/k") + + +@pytest.mark.parametrize( + ("segment", "windows", "problem"), + [ + ("a", False, None), + ("a", True, None), + ("a.b", True, None), + ("con", False, None), + ("a:b", False, None), + ("a\\b", False, None), + (f"a{RESERVED_SUFFIX}", False, "reserved"), + (f"a{RESERVED_SUFFIX}", True, "reserved"), + (f"a{RESERVED_SUFFIX.upper()}", False, "reserved"), + ("a:b", True, "forbids"), + ("a\\b", True, "forbids"), + ("a?", True, "forbids"), + ("a\x01", True, "forbids"), + ("NUL", True, "device"), + ("con", True, "device"), + ("com1.txt", True, "device"), + ("LPT9", True, "device"), + ("COM¹", True, "device"), + ("a.", True, "strips"), + ("a ", True, "strips"), + ], +) +def test_segment_problem(segment: str, windows: bool, problem: str | None) -> None: + found = segment_problem(segment, windows=windows) + if problem is None: + assert found is None + else: + assert found is not None + assert problem in found + + +@pytest.mark.parametrize("existing", [False, True]) +def test_create_makes_a_missing_root_and_keeps_an_existing_one( + tmp_path: Path, existing: bool +) -> None: + root = tmp_path / "a" / "b" + if existing: + root.mkdir(parents=True) + (root / "k").write_bytes(b"x") + store = Store(LocalBackend.create(root)) + assert root.is_dir() + assert list(store.list()) == (["k"] if existing else []) + + +def test_constructing_changes_nothing_on_disk(tmp_path: Path) -> None: + before = sorted(p.name for p in tmp_path.iterdir()) + LocalBackend(tmp_path) + assert sorted(p.name for p in tmp_path.iterdir()) == before + + +def test_missing_root_raises(tmp_path: Path) -> None: + with pytest.raises(FileNotFoundError, match="LocalBackend.create"): + LocalBackend(tmp_path / "missing") + + +@pytest.mark.parametrize("make", [LocalBackend, LocalBackend.create]) +def test_root_that_is_a_file_raises(tmp_path: Path, make: Callable[[Path], LocalBackend]) -> None: + (tmp_path / "file").write_bytes(b"x") + with pytest.raises(NotADirectoryError, match="is a file"): + make(tmp_path / "file") + + +def test_reserved_key_raises(tmp_path: Path) -> None: + with pytest.raises(InvalidKeyError, match="reserved"): + Store(LocalBackend(tmp_path)).put(f"a{RESERVED_SUFFIX}/b", b"x") + + +def test_overlong_key_raises(tmp_path: Path) -> None: + with pytest.raises(InvalidKeyError, match="too long"): + Store(LocalBackend(tmp_path)).put("a" * 1000, b"x") + + +def _create( + store: Store[LocalBackend], key: str, barrier: threading.Barrier, results: list[bool] +) -> None: + barrier.wait() + results.append(isinstance(store.put_if_absent(key, b"x"), Written)) + + +@pytest.mark.parametrize("overlapping_roots", [False, True]) +def test_concurrent_creates_through_overlapping_roots( + tmp_path: Path, overlapping_roots: bool +) -> None: + """Of many racing `put_if_absent` writes to one key, exactly one applies, even through + backends whose roots overlap.""" + outer = Store(LocalBackend(tmp_path)) + inner = Store(LocalBackend.create(tmp_path / "sub")) if overlapping_roots else outer / "sub" + for round_ in range(50): + key = f"k{round_}" + barrier = threading.Barrier(8) + results: list[bool] = [] + threads = [ + threading.Thread(target=_create, args=(store, path, barrier, results)) + for store, path in [(outer, f"sub/{key}"), (inner, key)] * 4 + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + assert results.count(True) == 1 + + +def _create_in_process(root: str, key: str, start: threading.Event) -> bool: + start.wait() + return isinstance(Store(LocalBackend(root)).put_if_absent(key, b"x"), Written) + + +def test_concurrent_creates_apply_once_across_processes(tmp_path: Path) -> None: + ctx = multiprocessing.get_context("spawn") + with ctx.Manager() as manager, ctx.Pool(4) as pool: + for round_ in range(5): + start = manager.Event() + pending = [ + pool.apply_async(_create_in_process, (str(tmp_path), f"k{round_}", start)) + for _ in range(4) + ] + start.set() + assert [p.get(timeout=60) for p in pending].count(True) == 1 + + +def _put_many(store: Store[LocalBackend], errors: list[BaseException]) -> None: + try: + for i in range(200): + store.put(f"d/k{i}", b"x") + except BaseException as e: # noqa: BLE001 -- the test reports any failure + errors.append(e) + + +def test_delete_dir_racing_put_never_breaks_the_put(tmp_path: Path) -> None: + """A put whose directory a concurrent `delete_dir` removes starts over instead of failing.""" + store = Store(LocalBackend(tmp_path)) + errors: list[BaseException] = [] + writer = threading.Thread(target=_put_many, args=(store, errors)) + writer.start() + while writer.is_alive(): + store.delete_dir("d") + time.sleep(0.0001) + writer.join() + assert errors == [] + + +def _hold_lock(directory: Path, held: threading.Event, release: threading.Event) -> None: + with _directory_lock(directory): + held.set() + release.wait() + + +def _record_lock_file(directory: Path, entered: threading.Event, saw: list[bool]) -> None: + with _directory_lock(directory): + saw.append((directory / f"lock{RESERVED_SUFFIX}").exists()) + entered.set() + + +def test_lock_waiter_retries_when_the_lock_file_is_removed(tmp_path: Path) -> None: + """A waiter that wakes holding a lock file someone removed takes the new lock file instead.""" + held, release, entered = threading.Event(), threading.Event(), threading.Event() + saw: list[bool] = [] + holder = threading.Thread(target=_hold_lock, args=(tmp_path, held, release)) + holder.start() + held.wait() + waiter = threading.Thread(target=_record_lock_file, args=(tmp_path, entered, saw)) + waiter.start() + time.sleep(0.1) + assert not entered.is_set() + (tmp_path / f"lock{RESERVED_SUFFIX}").unlink() + release.set() + holder.join() + waiter.join(timeout=5) + assert saw == [True] + + +class _FlakyReplace: + """`os.replace` that fails with the given errors first, then renames.""" + + def __init__(self, failures: list[OSError]) -> None: + self._failures = failures + self._real = os.replace + + def __call__(self, src: str | os.PathLike[str], dst: str | os.PathLike[str]) -> None: + if self._failures: + raise self._failures.pop() + self._real(src, dst) + + +def test_put_retries_a_rename_into_a_removed_directory( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + store = Store(LocalBackend(tmp_path)) + failures = [OSError(errno.ENOENT, "removed"), OSError(errno.EINVAL, "removed")] + monkeypatch.setattr(os, "replace", _FlakyReplace(failures)) + store.put("a/k", b"x") + result = store.get("a/k") + assert isinstance(result, Found) + assert bytes(result.value) == b"x" + + +class _PausedReplace: + """`os.replace` that, for one destination name, waits for a signal before renaming.""" + + def __init__(self, name: str) -> None: + self._name = name + self._real = os.replace + self.reached = threading.Event() + self.release = threading.Event() + + def __call__(self, src: str | os.PathLike[str], dst: str | os.PathLike[str]) -> None: + if os.fspath(dst).endswith(self._name): + self.reached.set() + self.release.wait() + self._real(src, dst) + + +@pytest.mark.parametrize("ancestor", ["", "P", "P/D"]) +def test_delete_dir_waits_for_a_write_in_progress( + tmp_path: Path, ancestor: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """`delete_dir` of any ancestor waits for a write that holds its directory's lock, then + removes what it wrote; a create after the delete applies.""" + store = Store(LocalBackend(tmp_path)) + store.put("P/D/other", b"x") + paused = _PausedReplace("/k") + monkeypatch.setattr(os, "replace", paused) + outcomes: dict[str, bool] = {} + barrier = threading.Barrier(1) + writer = threading.Thread(target=_put_outcome, args=(store, "P/D/k", barrier, outcomes)) + writer.start() + assert paused.reached.wait(5) + deleter = threading.Thread(target=store.delete_dir, args=(ancestor,)) + deleter.start() + time.sleep(0.2) + assert deleter.is_alive() + paused.release.set() + writer.join(5) + deleter.join(5) + assert outcomes == {"P/D/k": True} + assert not store.exists("P/D/k") + assert isinstance(store.put_if_absent("P/D/k", b"y"), Written) + + +def test_symlinked_directory_is_outside_the_tree_listings_and_delete_dir_walk( + tmp_path: Path, +) -> None: + """What lies beyond a symlink to a directory may lie outside the root: listings leave it out, + and `delete_dir` never deletes through it, at the link or below it.""" + outside = tmp_path / "outside" + (outside / "sub").mkdir(parents=True) + (outside / "sub" / "keep").write_bytes(b"x") + store = Store(LocalBackend.create(tmp_path / "root")) + (tmp_path / "root" / "link").symlink_to(outside) + assert (list(store.list()), list(store.list_dir())) == ([], []) + assert (list(store.list("link")), list(store.list_dir("link/sub"))) == ([], []) + store.delete_dir("link/sub") + store.delete_dir("link") + assert (outside / "sub" / "keep").exists() + + +def _swap_then_remove( + remove: Callable[[int, str], None], directory: Path, target: Path, parent_fd: int, name: str +) -> None: + """`_remove_subtree`, after swapping `directory` for a symlink to `target` when it comes up.""" + if name == directory.name: + shutil.rmtree(directory) + directory.symlink_to(target) + remove(parent_fd, name) + + +@pytest.mark.skipif(not _local._FD_WALK, reason="walks by path where there is no dir_fd") +def test_delete_dir_never_follows_a_directory_swapped_for_a_symlink_mid_walk( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Whoever can write the root can swap a directory for a symlink after `delete_dir` scanned its + parent; the walk removes the link, never what it points at.""" + outside = tmp_path / "outside" + outside.mkdir() + (outside / "keep").write_bytes(b"x") + root = tmp_path / "root" + store = Store(LocalBackend.create(root)) + store.put("e/sub/k", b"x") + swap = partial(_swap_then_remove, _local._remove_subtree, root / "e" / "sub", outside) + monkeypatch.setattr(_local, "_remove_subtree", swap) + store.delete_dir("e") + assert (outside / "keep").exists() + assert not (root / "e").exists() + + +@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="needs FIFOs") +def test_fifo_is_not_a_key(tmp_path: Path) -> None: + """A FIFO in a key's place reads as absent instead of blocking for a writer, and no write can + make it a directory.""" + store = Store(LocalBackend(tmp_path)) + os.mkfifo(tmp_path / "fifo") + assert isinstance(store.get("fifo"), Missing) + assert list(store.list()) == [] + with pytest.raises(KeyConflictError): + store.put("fifo/k", b"x") + + +def test_missing_parent_directory_is_not_a_conflict(tmp_path: Path) -> None: + """A directory a concurrent `delete_dir` removed is one a write recreates, not a key in the way; + only names that exist and aren't directories, or dangling symlinks, are.""" + backend = LocalBackend(tmp_path) + assert not backend._has_key_parent(tmp_path / "gone" / "deeper" / "k") + (tmp_path / "file").write_bytes(b"x") + assert backend._has_key_parent(tmp_path / "file" / "deeper" / "k") + + +@pytest.mark.parametrize("path", ["/etc/passwd", "../x", "a/../../x"]) +def test_backend_path_outside_the_root_raises(tmp_path: Path, path: str) -> None: + """The backend is public; it refuses paths `Store` would never hand it.""" + backend = LocalBackend.create(tmp_path / "root") + with pytest.raises(InvalidKeyError): + backend.get(path, None) + with pytest.raises(InvalidKeyError): + backend.delete_dir(path) + + +def test_symlink_to_a_file_is_a_key(tmp_path: Path) -> None: + (tmp_path / "target").write_bytes(b"x") + store = Store(LocalBackend.create(tmp_path / "root")) + (tmp_path / "root" / "link").symlink_to(tmp_path / "target") + assert list(store.list()) == ["link"] + assert list(store.list_dir()) == [Key("link")] + found = store.get("link") + assert isinstance(found, Found) + assert bytes(found.value) == b"x" + + +def test_dangling_symlink_is_not_a_key(tmp_path: Path) -> None: + store = Store(LocalBackend.create(tmp_path / "root")) + (tmp_path / "root" / "link").symlink_to(tmp_path / "nowhere") + assert (list(store.list()), store.exists("link")) == ([], False) + + +def test_put_under_a_symlink_loop_raises(tmp_path: Path) -> None: + store = Store(LocalBackend.create(tmp_path / "root")) + (tmp_path / "root" / "a").symlink_to("a") + with pytest.raises(KeyConflictError): + store.put("a/k", b"x") + + +def test_put_under_a_dangling_symlink_raises(tmp_path: Path) -> None: + store = Store(LocalBackend.create(tmp_path / "root")) + (tmp_path / "root" / "link").symlink_to(tmp_path / "nowhere") + with pytest.raises(KeyConflictError, match="dangling"): + store.put("link/k", b"x") + + +def test_delete_dir_removes_a_nested_backends_staging(tmp_path: Path) -> None: + outer = Store(LocalBackend(tmp_path)) + inner = Store(LocalBackend.create(tmp_path / "sub")) + inner.put("k", b"x") + outer.delete_dir("sub") + assert not (tmp_path / "sub").exists() + + +def _put_outcome( + store: Store[LocalBackend], key: str, barrier: threading.Barrier, outcomes: dict[str, bool] +) -> None: + barrier.wait() + try: + store.put(key, b"x") + outcomes[key] = True + except KeyConflictError: + outcomes[key] = False + + +def test_reclaim_never_removes_an_acknowledged_key(tmp_path: Path) -> None: + """A put of `a` racing a put of `a/b`, over a directory `a` a delete left empty: exactly one + applies, and the one that applied is stored.""" + store = Store(LocalBackend(tmp_path)) + for _ in range(300): + store.delete_dir("") + store.put("a/x", b"x") + store.delete("a/x") + barrier = threading.Barrier(2) + outcomes: dict[str, bool] = {} + threads = [ + threading.Thread(target=_put_outcome, args=(store, key, barrier, outcomes)) + for key in ("a", "a/b") + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + stored = set(store.list()) + assert sum(outcomes.values()) == 1 + assert stored == {key for key, applied in outcomes.items() if applied} + + +def _coarse(self: LocalBackend) -> bool: + return False + + +@pytest.mark.parametrize( + "write", + [ + lambda s: s.put_if_match("k", b"x", Generation(object())), + lambda s: s.delete_if_match("k", Generation(object())), + ], + ids=["put_if_match", "delete_if_match"], +) +def test_if_match_on_a_filesystem_that_rounds_times_raises( + tmp_path: Path, write: Callable[[Store[LocalBackend]], object], monkeypatch: pytest.MonkeyPatch +) -> None: + """Generations need exact times only to compare against; `put_if_absent` still works.""" + monkeypatch.setattr(LocalBackend, "_probe_exact_times", _coarse) + store = Store(LocalBackend(tmp_path)) + with pytest.raises(UnsupportedOperationError, match="rounds file times"): + write(store) + assert isinstance(store.put_if_absent("k", b"x"), Written) + + +def test_local_backends_over_the_same_data_overlap(tmp_path: Path) -> None: + """Different backend objects, one filesystem: equal or nested roots overlap, as does an obstore + `LocalStore` over the same directory.""" + root = Store(LocalBackend(tmp_path)) + assert root.overlaps(Store(LocalBackend(tmp_path))) + assert root.overlaps(Store(LocalBackend.create(tmp_path / "a"))) + assert (root / "a").overlaps(Store(LocalBackend.create(tmp_path / "a" / "b"))) + assert not (root / "x").overlaps(Store(LocalBackend.create(tmp_path / "a"))) + assert root.overlaps(Store(ObjectStoreBackend(LocalStore(tmp_path)))) + assert not Store(LocalBackend.create(tmp_path / "lat")).overlaps( + Store(LocalBackend.create(tmp_path / "lat_bnds")) + ) diff --git a/packages/zarr-storage/tests/experimental/test_memory.py b/packages/zarr-storage/tests/experimental/test_memory.py new file mode 100644 index 0000000000..18b53dbe68 --- /dev/null +++ b/packages/zarr-storage/tests/experimental/test_memory.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import pickle +from typing import TYPE_CHECKING + +from zarr_storage.experimental import Store +from zarr_storage.experimental.backends import MemoryBackend +from zarr_storage.experimental.testing import ( + ConditionalDeleteSuite, + ConditionalPutSuite, + ConditionalRaceSuite, + KeyAndDirectorySuite, + PickleSuite, + StoreSuite, + UniqueGenerationsSuite, +) + +if TYPE_CHECKING: + from pathlib import Path + + +class TestMemoryBackend( + StoreSuite, + UniqueGenerationsSuite, + ConditionalPutSuite, + ConditionalDeleteSuite, + ConditionalRaceSuite, + KeyAndDirectorySuite, + PickleSuite, +): + def make_store(self, directory: Path) -> Store[MemoryBackend]: + return Store(MemoryBackend()) + + +def test_pickled_copy_is_independent() -> None: + """A pickled memory store carries a copy of its values; writes to either don't reach the other.""" + store = Store(MemoryBackend()) + store.put("a", b"1") + copy = pickle.loads(pickle.dumps(store)) + copy.put("b", b"2") + store.put("c", b"3") + assert set(store.list()) == {"a", "c"} + assert set(copy.list()) == {"a", "b"} diff --git a/packages/zarr-storage/tests/experimental/test_obstore.py b/packages/zarr-storage/tests/experimental/test_obstore.py new file mode 100644 index 0000000000..6049784180 --- /dev/null +++ b/packages/zarr-storage/tests/experimental/test_obstore.py @@ -0,0 +1,319 @@ +from __future__ import annotations + +import asyncio +import pickle +from typing import TYPE_CHECKING + +import obstore +import pytest +from obstore.exceptions import GenericError +from obstore.store import HTTPStore, LocalStore, MemoryStore, S3Store + +from zarr_storage.experimental import ( + Found, + Generation, + ObjectMetadata, + RangeRequest, + Store, + Unchanged, +) +from zarr_storage.experimental.backends import LocalBackend, ObjectStoreBackend +from zarr_storage.experimental.backends import _obstore as obstore_backend +from zarr_storage.experimental.backends._obstore import _empty_read_or_raise, _generation +from zarr_storage.experimental.testing import ( + ConditionalPutSuite, + KeyAndDirectorySuite, + KeyDirectoryConflictSuite, + NoConditionalPutSuite, + PickleSuite, + StoreSuite, + UniqueGenerationsSuite, +) + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Callable + from pathlib import Path + + from obstore.store import ObjectStore + + +_SYNC_CALLS = ["get", "get_ranges", "head", "put", "delete", "list_with_delimiter", "copy"] + + +class _NotOnTheEventLoop: + """An obstore function that refuses to run on a thread that is running an event loop.""" + + def __init__(self, real: Callable[..., object]) -> None: + self._real = real + + def __call__(self, *args: object, **kwargs: object) -> object: + try: + asyncio.get_running_loop() + except RuntimeError: + return self._real(*args, **kwargs) + raise AssertionError("A blocking obstore call ran inside an async method.") + + +class NoBlockingCallsInAsyncRuns: + """Fail any async run of a test that makes a blocking obstore call.""" + + @pytest.fixture(autouse=True) + def _forbid_blocking_calls( + self, request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch + ) -> None: + callspec = getattr(request.node, "callspec", None) + params = {} if callspec is None else callspec.params + if "async" in (params.get("store"), params.get("api")): + for name in _SYNC_CALLS: + monkeypatch.setattr(obstore, name, _NotOnTheEventLoop(getattr(obstore, name))) + + +class TestObjectStoreMemory( + StoreSuite, + UniqueGenerationsSuite, + ConditionalPutSuite, + KeyAndDirectorySuite, + NoBlockingCallsInAsyncRuns, +): + def make_store(self, directory: Path) -> Store[ObjectStoreBackend]: + return Store(ObjectStoreBackend(MemoryStore())) + + +class TestObjectStoreLocal( + StoreSuite, + NoConditionalPutSuite, + KeyDirectoryConflictSuite, + PickleSuite, + NoBlockingCallsInAsyncRuns, +): + def make_store(self, directory: Path) -> Store[ObjectStoreBackend]: + return Store(ObjectStoreBackend(LocalStore(directory))) + + +_META = ObjectMetadata(10, _generation("e", None), None) + + +def test_refused_empty_read_is_empty() -> None: + result = _empty_read_or_raise(_META, RangeRequest(10, 12), GenericError("refused")) + assert isinstance(result, Found) + assert (bytes(result.value), result.generation) == (b"", _META.generation) + + +def test_refused_readable_range_reraises() -> None: + error = GenericError("refused") + with pytest.raises(GenericError, match="refused"): + _empty_read_or_raise(_META, RangeRequest(2, 5), error) + + +class _FailFor: + """An obstore function that raises a transient error for one path and works for the rest.""" + + def __init__(self, real: Callable[..., object], path: str) -> None: + self._real = real + self._path = path + + def __call__( + self, store: object, path: str | None = None, *args: object, **kwargs: object + ) -> object: + if path == self._path: + raise GenericError("injected: 503 Service Unavailable") + return self._real(store, path, *args, **kwargs) + + +def _list_a(store: Store[ObjectStoreBackend]) -> object: + return list(store.list("a")) + + +def _list_dir_a(store: Store[ObjectStoreBackend]) -> object: + return list(store.list_dir("a")) + + +def _get_ab(store: Store[ObjectStoreBackend]) -> object: + return store.get("a/b") + + +def _head_ab(store: Store[ObjectStoreBackend]) -> object: + return store.head("a/b") + + +async def _collect(items: AsyncIterator[object]) -> list[object]: + return [item async for item in items] + + +def _list_a_async(store: Store[ObjectStoreBackend]) -> object: + return asyncio.run(_collect(store.as_async().list("a"))) + + +def _list_dir_a_async(store: Store[ObjectStoreBackend]) -> object: + return asyncio.run(_collect(store.as_async().list_dir("a"))) + + +def _get_ab_async(store: Store[ObjectStoreBackend]) -> object: + return asyncio.run(store.as_async().get("a/b")) + + +@pytest.mark.parametrize( + ("operation", "failing", "path"), + [ + (_list_a, "list", "a"), + (_list_dir_a, "list_with_delimiter", "a"), + (_get_ab, "get", "a/b"), + (_head_ab, "head", "a/b"), + (_list_a_async, "list", "a"), + (_list_dir_a_async, "list_with_delimiter_async", "a"), + (_get_ab_async, "get_async", "a/b"), + ], + ids=["list", "list_dir", "get", "head", "list_async", "list_dir_async", "get_async"], +) +def test_errors_on_object_stores_are_not_read_as_absent( + operation: Callable[[Store[ObjectStoreBackend]], object], + failing: str, + path: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Only a filesystem store's refusals mean "under a key"; elsewhere an error is an error. + + Only the operation's own call fails, so a check of the path's parents would succeed and could + wrongly turn the error into "absent". + """ + store = Store(ObjectStoreBackend(MemoryStore())) + store.put("a", b"x") + store.put("a/b", b"x") + monkeypatch.setattr(obstore, failing, _FailFor(getattr(obstore, failing), path)) + with pytest.raises(GenericError): + operation(store) + + +def _no_if_none_match(generation: object) -> dict[str, str]: + return {} + + +@pytest.mark.parametrize("api", ["sync", "async"]) +def test_get_if_changed_without_if_none_match_is_unchanged( + api: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """A store that can't skip the read (it ignores `If-None-Match`) still reports `Unchanged` for + a value that has the generation.""" + monkeypatch.setattr(obstore_backend, "_if_none_match", _no_if_none_match) + store = Store(ObjectStoreBackend(MemoryStore())) + generation = store.put("k", b"x").generation + if api == "sync": + result = store.get_if_changed("k", generation) + else: + result = asyncio.run(store.as_async().get_if_changed("k", generation)) + assert result == Unchanged(generation, result.read_at) + + +def _no_identity(e_tag: str | None, version: str | None) -> Generation: + return Generation(("obstore", None, None)) + + +@pytest.mark.parametrize("api", ["sync", "async"]) +def test_get_if_changed_of_a_store_without_etags_or_versions_reads_the_value( + api: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """A store that reports neither (an HTTP server that sends no ETag) gives every value one + generation, which can't show that a value is unchanged.""" + monkeypatch.setattr(obstore_backend, "_generation", _no_identity) + store = Store(ObjectStoreBackend(MemoryStore())) + generation = store.put("k", b"old").generation + store.put("k", b"new") + if api == "sync": + result = store.get_if_changed("k", generation) + else: + result = asyncio.run(store.as_async().get_if_changed("k", generation)) + assert isinstance(result, Found) + assert bytes(result.value) == b"new" + + +def _s3(bucket: str, prefix: str | None = None) -> Store[ObjectStoreBackend]: + return Store(ObjectStoreBackend(S3Store(bucket, prefix=prefix, region="us-east-1"))) + + +def _http(url: str) -> Store[ObjectStoreBackend]: + return Store(ObjectStoreBackend(HTTPStore.from_url(url))) + + +def _endpoint(endpoint: str) -> Store[ObjectStoreBackend]: + return Store(ObjectStoreBackend(S3Store("b", region="us-east-1", endpoint=endpoint))) + + +def _minio(bucket: str) -> Store[ObjectStoreBackend]: + store = S3Store(bucket, region="us-east-1", endpoint="http://minio:9000") + return Store(ObjectStoreBackend(store)) + + +@pytest.mark.parametrize( + ("left", "right", "overlaps"), + [ + (_s3("b"), _s3("b"), True), + (_s3("b", "p"), _s3("b", "p/q"), True), + (_s3("b", "p"), _s3("b", "q"), False), + (_s3("b"), _s3("c"), False), + (_minio("b"), _s3("b"), False), + (Store(ObjectStoreBackend(MemoryStore())), Store(ObjectStoreBackend(MemoryStore())), False), + (_http("https://example.com/d"), _http("https://example.com/d/"), True), + (_http("https://example.com/d"), _http("https://example.com/d/sub"), True), + (_http("https://example.com/d"), _http("https://example.com/e"), False), + (_http("https://example.com/d"), _http("https://example.org/d"), False), + (_endpoint("http://localhost:9000"), _endpoint("http://localhost:9000/"), True), + (_endpoint("http://h:80"), _endpoint("http://h"), True), + (_endpoint("http://[::1]:9000"), _endpoint("http://[::1:9000]"), False), + (_http("https://h/a//b"), _http("https://h/a/b"), True), + (_http("https://h/a%20b"), _http("https://h/") / "a b", True), + (_http("https://h/a%00b"), _http("https://h/a"), False), + ], +) +def test_object_store_locations( + left: Store[ObjectStoreBackend], right: Store[ObjectStoreBackend], overlaps: bool +) -> None: + """Different backend objects over one bucket and prefix see the same keys; a memory store is a + space of its own, even though obstore's stores compare equal by configuration.""" + assert left.overlaps(right) is overlaps + + +@pytest.mark.parametrize( + "store", + [ + S3Store("b", region="us-east-1", access_key_id="AKIA", secret_access_key="secret"), + S3Store("b", region="us-east-1", endpoint="http://user:secret@localhost:9000"), + HTTPStore.from_url("https://user:secret@example.com/data"), + HTTPStore.from_url("https://example.com/data?sig=secret"), + ], + ids=["s3-keys", "endpoint-userinfo", "url-userinfo", "presigned-query"], +) +def test_object_store_location_has_no_credentials(store: ObjectStore) -> None: + assert "secret" not in repr(Store(ObjectStoreBackend(store)).location) + + +def test_local_store_location_is_fixed_when_the_backend_is_made( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A relative `LocalStore` prefix resolves once, as the store's own does, so changing directory + later doesn't move the location away from where writes land.""" + (tmp_path / "data").mkdir() + monkeypatch.chdir(tmp_path) + store = Store(ObjectStoreBackend(LocalStore("data"))) + monkeypatch.chdir(tmp_path / "data") + assert store.overlaps(Store(LocalBackend(tmp_path / "data"))) + + +def test_pickled_local_store_location_follows_where_it_writes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Unpickled elsewhere, a `LocalStore` resolves a relative prefix again; its location follows.""" + for directory in ("x/rel", "y/rel"): + (tmp_path / directory).mkdir(parents=True) + monkeypatch.chdir(tmp_path / "x") + pickled = pickle.dumps(Store(ObjectStoreBackend(LocalStore("rel")))) + monkeypatch.chdir(tmp_path / "y") + store = pickle.loads(pickled) + store.put("k", b"x") + assert (tmp_path / "y" / "rel" / "k").exists() + assert store.overlaps(Store(LocalBackend(tmp_path / "y" / "rel"))) + + +def test_endpoint_with_a_port_that_is_not_a_number_still_constructs() -> None: + store = S3Store("b", region="us-east-1", endpoint="http://user:secret@localhost:abc") + location = Store(ObjectStoreBackend(store)).location + assert "secret" not in repr(location) diff --git a/packages/zarr-storage/tests/experimental/test_package.py b/packages/zarr-storage/tests/experimental/test_package.py new file mode 100644 index 0000000000..c0e0afcbdf --- /dev/null +++ b/packages/zarr-storage/tests/experimental/test_package.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +import subprocess +import sys + +ALONE = """ +import sys +import zarr_storage.experimental.backends._obstore +import zarr_storage.experimental.testing +unwanted = {"numpy", "donfig", "packaging", "fsspec", "zarr", "zarr_storage.legacy"} +assert not unwanted & sys.modules.keys() +""" + + +def test_imports_without_the_legacy_api() -> None: + """The experimental API knows nothing about Zarr: neither the legacy code nor its dependencies.""" + subprocess.run([sys.executable, "-c", ALONE], check=True) diff --git a/packages/zarr-storage/tests/experimental/test_resources.py b/packages/zarr-storage/tests/experimental/test_resources.py new file mode 100644 index 0000000000..103ff03f8c --- /dev/null +++ b/packages/zarr-storage/tests/experimental/test_resources.py @@ -0,0 +1,577 @@ +"""Contexts and their resources, alone and as stores draw on them.""" + +from __future__ import annotations + +import asyncio +import pickle +import threading +import time +from functools import partial, partialmethod +from typing import TYPE_CHECKING + +import pytest +from obstore.store import MemoryStore + +from zarr_storage.experimental import ( + AsyncStore, + Context, + Found, + FoundRanges, + Generation, + Limiter, + Missing, + ObjectMetadata, + Store, + ThreadPool, + Unchanged, +) +from zarr_storage.experimental._resources import _ThreadWaiter, default_limiter +from zarr_storage.experimental.backends import LocalBackend, MemoryBackend, ObjectStoreBackend + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + from pathlib import Path + + from zarr_storage.experimental import ByteRange + from zarr_storage.experimental.testing import FullBackend + + +class _Peak: + """Counts callers inside a region, and the most there ever were at once.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self._inside = 0 + self.most = 0 + self.done = 0 + + def enter(self) -> None: + with self._lock: + self._inside += 1 + self.most = max(self.most, self._inside) + + def leave(self) -> None: + with self._lock: + self._inside -= 1 + self.done += 1 + + +def _hold_sync(limiter: Limiter, peaks: list[_Peak]) -> None: + with limiter.slot(): + for peak in peaks: + peak.enter() + time.sleep(0.002) + for peak in peaks: + peak.leave() + + +async def _hold_async(limiter: Limiter, peak: _Peak) -> None: + async with limiter.slot(): + peak.enter() + await asyncio.sleep(0.002) + peak.leave() + + +async def _many_async(limiter: Limiter, peak: _Peak, n: int) -> None: + await asyncio.gather(*(_hold_async(limiter, peak) for _ in range(n))) + + +def _run_loop(limiter: Limiter, peak: _Peak, n: int) -> None: + asyncio.run(_many_async(limiter, peak, n)) + + +def _finishes(fn: Callable[[], object]) -> bool: + """Whether `fn()` returns within ten seconds; a deadlock fails a test instead of hanging it.""" + worker = threading.Thread(target=fn, daemon=True) + worker.start() + worker.join(10) + return not worker.is_alive() + + +def _join_all(threads: list[threading.Thread]) -> None: + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + +# ---------------------------------------------------------------------------- Limiter + + +@pytest.mark.parametrize("limit", [1, 3]) +def test_limiter_bounds_threads_and_tasks_together(limit: int) -> None: + """Threads and tasks on two event loops never hold more than `limit` slots at once.""" + limiter, peak = Limiter(limit), _Peak() + workers = [threading.Thread(target=_hold_sync, args=(limiter, [peak])) for _ in range(8)] + workers += [threading.Thread(target=_run_loop, args=(limiter, peak, 8)) for _ in range(2)] + _join_all(workers) + assert (peak.done, peak.most, limiter.in_use) == (24, limit, 0) + + +def test_nested_limiter_holds_slots_of_both() -> None: + """A limiter `within` another is bounded by its own limit, and shares the wider one.""" + wide = Limiter(3) + narrow = Limiter(2, within=wide) + narrow_peak, wide_peak = _Peak(), _Peak() + workers = [ + threading.Thread(target=_hold_sync, args=(narrow, [narrow_peak, wide_peak])) + for _ in range(8) + ] + workers += [threading.Thread(target=_hold_sync, args=(wide, [wide_peak])) for _ in range(8)] + _join_all(workers) + assert (narrow_peak.most, wide_peak.most, wide_peak.done) == (2, 3, 16) + assert (narrow.in_use, wide.in_use) == (0, 0) + + +def _wait_for_slot(limiter: Limiter) -> None: + with limiter.slot(): + pass + + +def test_waiting_on_a_narrow_limit_holds_none_of_the_wide_one() -> None: + """Slots are taken innermost first, so a burst queued on a narrow limit leaves the wide one + free for everyone else.""" + wide = Limiter(2) + narrow = Limiter(1, within=wide) + with narrow.slot(): + waiter = threading.Thread(target=_wait_for_slot, args=(narrow,)) + waiter.start() + waiter.join(0.05) + assert waiter.is_alive() + assert wide.in_use == 1 + waiter.join(10) + assert (narrow.in_use, wide.in_use) == (0, 0) + + +async def _take_in_order(limiter: Limiter, name: str, order: list[str]) -> None: + async with limiter.slot(): + order.append(name) + + +async def _first_come_first_served() -> list[str]: + limiter, order = Limiter(1), [] + await limiter.acquire_async() + tasks = [asyncio.create_task(_take_in_order(limiter, name, order)) for name in "abc"] + await asyncio.sleep(0) + limiter.release() + await asyncio.gather(*tasks) + return order + + +def test_limiter_serves_waiters_in_order() -> None: + assert asyncio.run(_first_come_first_served()) == ["a", "b", "c"] + + +async def _cancel_while_waiting(granted_first: bool) -> int: + limiter = Limiter(1) + await limiter.acquire_async() + waiting = asyncio.create_task(limiter.acquire_async()) + await asyncio.sleep(0) + if granted_first: + limiter.release() # the slot passes to the waiter, which is then cancelled + waiting.cancel() + with pytest.raises(asyncio.CancelledError): + await waiting + if not granted_first: + limiter.release() + return limiter.in_use + + +@pytest.mark.parametrize("granted_first", [False, True]) +def test_cancelled_waiter_gives_back_its_slot(granted_first: bool) -> None: + assert asyncio.run(_cancel_while_waiting(granted_first)) == 0 + + +async def _cancel_between_slots() -> tuple[int, int]: + wide = Limiter(1) + narrow = Limiter(1, within=wide) + await wide.acquire_async() + entering = asyncio.create_task(_wait_for_slot_async(narrow)) + await asyncio.sleep(0) # holds the narrow slot, waits for the wide one + entering.cancel() + with pytest.raises(asyncio.CancelledError): + await entering + wide.release() + return narrow.in_use, wide.in_use + + +async def _wait_for_slot_async(limiter: Limiter) -> None: + async with limiter.slot(): + pass + + +def test_cancelled_while_taking_a_nested_slot_gives_back_the_inner_one() -> None: + assert asyncio.run(_cancel_between_slots()) == (0, 0) + + +def _interrupt_wait(waiter: _ThreadWaiter, granted_first: bool) -> None: + """A stand-in for `_ThreadWaiter.wait` that a KeyboardInterrupt ends, after the grant or + before it.""" + if granted_first: + waiter._event.wait() + raise KeyboardInterrupt + + +@pytest.mark.parametrize("granted_first", [False, True]) +def test_interrupted_thread_waiter_gives_back_its_slot( + granted_first: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + """Ctrl-C while a thread waits for a slot must not lose the slot to a waiter that's gone.""" + limiter = Limiter(1) + limiter.acquire() + monkeypatch.setattr(_ThreadWaiter, "wait", partialmethod(_interrupt_wait, granted_first)) + if granted_first: + threading.Timer(0.05, limiter.release).start() + with pytest.raises(KeyboardInterrupt): + limiter.acquire() + if not granted_first: + limiter.release() + assert limiter.in_use == 0 + + +@pytest.mark.parametrize(("limit", "error"), [(0, ValueError), (1.5, TypeError), (True, TypeError)]) +def test_limiter_of_a_bad_limit_raises(limit: object, error: type[Exception]) -> None: + with pytest.raises(error): + Limiter(limit) # pyright: ignore[reportArgumentType] + + +def test_releasing_a_slot_not_held_raises() -> None: + with pytest.raises(RuntimeError, match="not held"): + Limiter(1).release() + + +# ---------------------------------------------------------------------------- ThreadPool + + +def _worker_view(pool: ThreadPool, other: ThreadPool) -> tuple[bool, bool]: + return pool.in_worker(), other.in_worker() + + +def test_thread_pool_knows_its_own_threads() -> None: + pool, other = ThreadPool(1), ThreadPool(1) + try: + assert not pool.in_worker() + assert pool.submit(_worker_view, pool, other).result() == (True, False) + finally: + pool.shutdown() + other.shutdown() + + +@pytest.mark.parametrize(("size", "error"), [(0, ValueError), (2.0, TypeError)]) +def test_thread_pool_of_a_bad_size_raises(size: object, error: type[Exception]) -> None: + with pytest.raises(error): + ThreadPool(size) # pyright: ignore[reportArgumentType] + + +def _run_on_own_thread(pool: ThreadPool) -> bool: + return asyncio.run(pool.run(pool.in_worker)) + + +def test_run_on_a_thread_of_its_own_pool_runs_inline() -> None: + """Queued behind itself on a one-thread pool, the work would never start.""" + pool = ThreadPool(1) + try: + assert pool.submit(_run_on_own_thread, pool).result(timeout=10) is True + finally: + pool.shutdown() + + +def test_shutting_down_the_default_pool_raises() -> None: + with pytest.raises(ValueError, match="shared"): + ThreadPool.default().shutdown() + + +# ---------------------------------------------------------------------------- Context + + +def test_context_resolves_resources_through_its_parents() -> None: + """Own resources first, then the parent's, then the process-wide defaults.""" + pool, a, b = ThreadPool(2), Limiter(4), Limiter(5) + default = Context.default() + assert default.threads is ThreadPool.default() + assert default.limiter("x") is default_limiter("x") + own = Context(threads=pool, limits={"a": a}) + assert (own.threads, own.limiter("a"), own.limiter("x")) == (pool, a, default_limiter("x")) + child = own.child(limits={"b": b}) + assert (child.threads, child.limiter("a"), child.limiter("b")) == (pool, a, b) + assert child.child(threads=ThreadPool.default()).threads is ThreadPool.default() + narrowed = child.limited("a", 2).limiter("a") + assert (narrowed.limit, narrowed.within) == (2, a) + + +@pytest.mark.parametrize( + "make", + [ + partial(Context, limits={"a": 4}), # pyright: ignore[reportArgumentType] + partial(Context, threads=4), # pyright: ignore[reportArgumentType] + ], + ids=["limit-not-a-limiter", "threads-not-a-pool"], +) +def test_context_of_a_bad_resource_raises(make: Callable[[], Context]) -> None: + with pytest.raises(TypeError): + make() + + +def test_views_carry_their_context() -> None: + """Views keep their context; `with_context` and `limited` change it and nothing else.""" + context = Context(limits={"memory": Limiter(8)}) + store = Store(MemoryBackend(), context=context) / "r" + for view in (store / "a", store.as_read_only(), store.as_async(), store.as_async().as_sync()): + assert view.context is context + other = Context() + assert store.with_context(other).context is other + limited = store.limited(2) + assert limited.context.parent is context + assert limited.context.limiter("memory").limit == 2 + assert limited.context.limiter("memory").within is context.limiter("memory") + assert (limited.root, limited.shares_backend(store)) == ("r", True) + + +def test_pickling_keeps_resources_shared(tmp_path: Path) -> None: + """Stores that shared a context share one after a round trip; defaults stay defaults.""" + wide = Limiter(8) + context = Context(threads=ThreadPool(2), limits={"local": Limiter(3, within=wide)}) + stores = ( + Store(LocalBackend.create(tmp_path / "a"), context=context), + Store(LocalBackend.create(tmp_path / "b"), context=context), + Store(LocalBackend.create(tmp_path / "c")), + ) + a, b, c = pickle.loads(pickle.dumps(stores)) + assert a.context is b.context + assert a.context is not context + limiter = a.context.limiter("local") + assert (a.context.threads.max_workers, limiter.limit, limiter.within.limit) == (2, 3, 8) + assert c.context is Context.default() + + +# ---------------------------------------------------------------------------- stores under limits + + +def _get_in_thread(store: Store[FullBackend], results: list[object]) -> None: + results.append(store.get("k")) + + +async def _get_async_while_held(store: Store[FullBackend]) -> bool: + try: + await asyncio.wait_for(store.as_async().get("k"), 0.05) + except TimeoutError: + return True + return False + + +@pytest.mark.parametrize("backend", ["local", "obstore"]) +def test_operations_wait_for_the_contexts_limiter(tmp_path: Path, backend: str) -> None: + """Sync and async operations, on native-async and sync-only backends, wait for a slot.""" + raw: FullBackend = ( + LocalBackend(tmp_path) if backend == "local" else ObjectStoreBackend(MemoryStore()) + ) + pool, limiter = ThreadPool(2), Limiter(1) + store = Store(raw, context=Context(threads=pool, limits={raw.resource_key: limiter})) + store.put("k", b"x") + limiter.acquire() # some other operation under this context holds the only slot + results: list[object] = [] + reader = threading.Thread(target=_get_in_thread, args=(store, results)) + reader.start() + reader.join(0.05) + assert reader.is_alive() + assert asyncio.run(_get_async_while_held(store)) + limiter.release() + reader.join(10) + pool.shutdown() # the timed-out async read's thread finishes too + assert isinstance(results[0], Found) + assert limiter.in_use == 0 + + +class _PeakBackend(MemoryBackend): + """A memory backend whose reads take a moment and record how many overlap.""" + + def __init__(self) -> None: + super().__init__() + self.peak = _Peak() + + def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + self.peak.enter() + time.sleep(0.005) + self.peak.leave() + return super().get(path, byte_range) + + +def test_limited_view_bounds_its_batches() -> None: + backend = _PeakBackend() + store = Store(backend, context=Context(threads=ThreadPool(8))) + keys = [f"k{i}" for i in range(24)] + store.put_many((key, b"x") for key in keys) + assert len(list(store.limited(2).get_many(keys))) == 24 + assert backend.peak.most == 2 + backend.peak.most = 0 + assert len(list(store.get_many(keys))) == 24 + assert backend.peak.most > 2 + + +class _RecordingBackend(LocalBackend): + """A local backend that records which threads its reads run on.""" + + def __init__(self, root: Path) -> None: + super().__init__(root) + self.read_on: set[int] = set() + + def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + self.read_on.add(threading.get_ident()) + return super().get(path, byte_range) + + +def _batch_here(store: Store[_RecordingBackend], keys: list[str]) -> int: + assert all(isinstance(result, Found) for _, result in store.get_many(keys)) + return threading.get_ident() + + +def test_batch_from_a_thread_of_its_own_pool_runs_on_that_thread(tmp_path: Path) -> None: + """A batch started on one of its pool's threads must not wait for the pool's other threads, + which may all be waiting the same way; it runs its reads on the thread that started it.""" + pool = ThreadPool(2) + backend = _RecordingBackend(tmp_path) + store = Store(backend, context=Context(threads=pool)) + keys = [f"k{i}" for i in range(4)] + store.put_many((key, b"x") for key in keys) + backend.read_on.clear() + try: + worker = pool.submit(_batch_here, store, keys).result(timeout=10) + finally: + pool.shutdown(wait=False) + assert backend.read_on == {worker} + + +def _read_batch(store: Store[LocalBackend], results: list[object]) -> None: + results.extend(result for _, result in store.get_many(["k"])) + + +def _read_async(store: Store[LocalBackend], results: list[object]) -> None: + results.append(asyncio.run(store.as_async().get("k"))) + + +def _settle() -> None: + time.sleep(0.05) + + +def test_async_read_of_a_sync_backend_holds_no_slot_while_it_waits_for_a_thread( + tmp_path: Path, +) -> None: + """One thread, one slot. A sync batch's read is queued on the thread, then an async read of the + sync backend is queued behind it. Had the async read taken the slot before its turn on the + thread, the batch's read, which runs first, would wait for that slot forever.""" + pool, limiter = ThreadPool(1), Limiter(1) + store = Store(LocalBackend(tmp_path), context=Context(threads=pool, limits={"local": limiter})) + store.put("k", b"x") + gate = threading.Event() + pool.submit(gate.wait) # keeps the only thread busy while the reads queue up + batch: list[object] = [] + single: list[object] = [] + batch_reader = threading.Thread(target=_read_batch, args=(store, batch), daemon=True) + async_reader = threading.Thread(target=_read_async, args=(store, single), daemon=True) + batch_reader.start() + _settle() # the batch's read is queued + async_reader.start() + _settle() # the async read is queued behind it + gate.set() + batch_reader.join(10) + async_reader.join(10) + assert not batch_reader.is_alive() + assert not async_reader.is_alive() + assert [type(r) for r in batch + single] == [Found, Found] + assert limiter.in_use == 0 + + +def _sync_get(store: Store[LocalBackend]) -> object: + return store.get("k") + + +async def _sync_op_on_the_pool_beside_an_async_op(store: Store[LocalBackend]) -> list[object]: + pool = store.context.threads + on_pool = asyncio.wrap_future(pool.submit(_sync_get, store)) + return [await store.as_async().get("k"), await on_pool] + + +def test_sync_operation_on_a_pool_thread_beside_an_async_operation_finishes( + tmp_path: Path, +) -> None: + """One thread, one slot: a sync operation running on the pool waits for the slot while an async + operation of a sync backend waits for the thread. Neither may hold what the other waits for, + which is why slots are taken on the pool thread, not before the work goes to the pool.""" + pool, limiter = ThreadPool(1), Limiter(1) + store = Store(LocalBackend(tmp_path), context=Context(threads=pool, limits={"local": limiter})) + store.put("k", b"x") + results: list[object] = [] + try: + assert _finishes( + lambda: results.extend(asyncio.run(_sync_op_on_the_pool_beside_an_async_op(store))) + ) + finally: + pool.shutdown(wait=False) + assert [type(r) for r in results] == [Found, Found] + + +async def _cancel_write_waiting_for_its_slot(store: AsyncStore[LocalBackend]) -> None: + limited = store.limited(1) + limiter = limited.context.limiter("local") + limiter.acquire() # held elsewhere, so the write waits for its slot + write = asyncio.ensure_future(limited.put("k", b"old")) + await asyncio.sleep(0.05) + write.cancel() + with pytest.raises(asyncio.CancelledError): + await write + limiter.release() + await asyncio.sleep(0.05) + + +def test_cancelled_write_of_a_sync_backend_never_lands(tmp_path: Path) -> None: + """A write cancelled while it waits for its slot doesn't run later, after the caller moved on.""" + store = AsyncStore(LocalBackend(tmp_path)) + asyncio.run(_cancel_write_waiting_for_its_slot(store)) + assert isinstance(store.as_sync().get("k"), Missing) + + +class _AsyncReadsSyncWrites(LocalBackend): + """A backend whose reads are natively async (and slow) while its writes are sync.""" + + async def get_async(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + await asyncio.sleep(0.1) + return self.get(path, byte_range) + + async def get_if_changed_async( + self, path: str, generation: Generation, byte_range: ByteRange | None + ) -> Found | Missing | Unchanged: + return self.get_if_changed(path, generation, byte_range) + + async def get_ranges_async( + self, path: str, ranges: Sequence[ByteRange] + ) -> FoundRanges | Missing: + return self.get_ranges(path, ranges) + + async def head_async(self, path: str) -> ObjectMetadata | Missing: + return self.head(path) + + +async def _write_after(store: AsyncStore[_AsyncReadsSyncWrites]) -> object: + await asyncio.sleep(0.02) # the read holds the only slot by now + return await store.put("k", b"2") + + +async def _read_and_write(store: AsyncStore[_AsyncReadsSyncWrites]) -> list[object]: + return list(await asyncio.gather(store.get("k"), _write_after(store))) + + +def _loop_on_this_thread(store: AsyncStore[_AsyncReadsSyncWrites]) -> list[object]: + return asyncio.run(_read_and_write(store)) + + +def test_event_loop_on_a_pool_thread_waits_for_slots_without_blocking(tmp_path: Path) -> None: + """On a loop running inside the pool's work, a sync operation waits for its slot as a task: + blocking the loop's thread would stop the task holding the slot from ever giving it back.""" + pool = ThreadPool(2) + store = AsyncStore(_AsyncReadsSyncWrites(tmp_path), context=Context(threads=pool)).limited(1) + store.as_sync().put("k", b"1") + try: + results = pool.submit(_loop_on_this_thread, store).result(timeout=10) + finally: + pool.shutdown(wait=False) + assert [type(r).__name__ for r in results] == ["Found", "Written"] diff --git a/packages/zarr-storage/tests/experimental/test_store.py b/packages/zarr-storage/tests/experimental/test_store.py new file mode 100644 index 0000000000..cdb3cb92cc --- /dev/null +++ b/packages/zarr-storage/tests/experimental/test_store.py @@ -0,0 +1,422 @@ +"""`Store` behavior that doesn't depend on a backend's own implementation.""" + +from __future__ import annotations + +import asyncio +import copy +import pickle +from typing import TYPE_CHECKING + +import pytest + +from zarr_storage.experimental import ( + AsyncStore, + BatchError, + Copied, + Found, + FoundRanges, + Generation, + InvalidKeyError, + Location, + Missing, + ObjectMetadata, + OffsetRequest, + RangeRequest, + ReadOnlyError, + Store, + SuffixRequest, + Unchanged, + Written, +) +from zarr_storage.experimental._byte_range import resolve +from zarr_storage.experimental.backends import MemoryBackend + +if TYPE_CHECKING: + from collections.abc import Iterator, Sequence + + from zarr_storage.experimental import ByteRange, Context + + +class _ReadOnlyBackend: + """A backend with only the `Readable` capability, over a fixed dict.""" + + def __init__(self, values: dict[str, bytes]) -> None: + self._values = values + + @property + def resource_key(self) -> str: + return "test" + + @property + def location(self) -> Location: + return Location(("test", id(self)), "") + + @property + def closed(self) -> bool: + return False + + @property + def writable(self) -> bool: + return False + + def close(self) -> None: + pass + + def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + data = self._values.get(path) + if data is None: + return Missing() + start, end = resolve(byte_range, len(data)) + return Found(memoryview(data)[start:end], Generation(0)) + + def get_if_changed( + self, path: str, generation: Generation, byte_range: ByteRange | None + ) -> Found | Missing | Unchanged: + raise NotImplementedError + + def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> FoundRanges | Missing: + raise NotImplementedError + + def head(self, path: str) -> ObjectMetadata | Missing: + data = self._values.get(path) + return Missing() if data is None else ObjectMetadata(len(data), Generation(0), None) + + +class _DeviceBuffer: + """Stands in for device memory (a GPU array): no buffer protocol, so host code can't view it.""" + + def __init__(self, size: int) -> None: + self._data = bytearray(size) + + def __len__(self) -> int: + return len(self._data) + + def upload(self, data: memoryview) -> None: + self._data[: len(data)] = data + + def download(self, n: int) -> bytes: + return bytes(self._data[:n]) + + +class _DeviceBackend(_ReadOnlyBackend): + """A backend that reads into `_DeviceBuffer`s only, as a GPU direct storage backend would.""" + + def get_into( + self, path: str, out: _DeviceBuffer, byte_range: ByteRange | None + ) -> Copied | Missing: + found = self.get(path, byte_range) + if isinstance(found, Missing): + return found + if len(found.value) > len(out): + raise ValueError("The output buffer is too short.") + out.upload(found.value) + return Copied(len(found.value), found.generation) + + +@pytest.mark.parametrize( + ("byte_range", "expected"), + [(None, b"0123"), (RangeRequest(1, 3), b"12"), (SuffixRequest(1), b"3")], +) +def test_get_into_a_device_buffer(byte_range: ByteRange | None, expected: bytes) -> None: + """`get_into` takes the buffer type the backend reads into, and applies the store's root.""" + store = Store(_DeviceBackend({"a/k": b"0123"})) / "a" + out = _DeviceBuffer(4) + assert store.get_into("k", out, byte_range=byte_range) == Copied(len(expected), Generation(0)) + assert out.download(len(expected)) == expected + assert store.get_into("missing", out) == Missing() + + +def test_get_into_many_device_buffers() -> None: + """Without a batch method of its own, the backend's `get_into` serves `get_into_many`.""" + store = Store(_DeviceBackend({"a/k": b"0123", "a/j": b"45"})) / "a" + whole, part = _DeviceBuffer(4), _DeviceBuffer(1) + results = { + request[0]: result + for request, result in store.get_into_many( + [("k", whole), ("j", part, SuffixRequest(1)), ("missing", _DeviceBuffer(1))] + ) + } + assert results == { + "k": Copied(4, Generation(0)), + "j": Copied(1, Generation(0)), + "missing": Missing(), + } + assert (whole.download(4), part.download(1)) == (b"0123", b"5") + + +class _BatchBackend(_ReadOnlyBackend): + """A backend with its own `get_many`, which answers in reverse and records what it was asked.""" + + def __init__(self, values: dict[str, bytes]) -> None: + super().__init__(values) + self.asked: list[tuple[str, ByteRange | None]] = [] + + def get_many( + self, requests: Sequence[tuple[str, ByteRange | None]], context: Context + ) -> Iterator[tuple[int, Found | Missing]]: + self.asked.extend(requests) + for index in reversed(range(len(requests))): + yield index, self.get(*requests[index]) + + +def test_get_many_uses_the_backends_batch_method() -> None: + backend = _BatchBackend({"r/a": b"0123"}) + results = list((Store(backend) / "r").get_many(["a", ("a", RangeRequest(1, 2)), "b"])) + assert backend.asked == [("r/a", None), ("r/a", RangeRequest(1, 2)), ("r/b", None)] + assert [(request, type(result)) for request, result in results] == [ + ("b", Missing), + (("a", RangeRequest(1, 2)), Found), + ("a", Found), + ] + + +class _FailingBackend(MemoryBackend): + """A memory backend whose `put` and `get` raise for the path `"r/bad"`.""" + + def __init__(self) -> None: + super().__init__() + self.attempted: list[str] = [] + + def put(self, path: str, value: memoryview) -> Written: + self.attempted.append(path) + if path == "r/bad": + raise OSError("refused") + return super().put(path, value) + + def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + self.attempted.append(path) + if path == "r/bad": + raise OSError("refused") + return super().get(path, byte_range) + + +def test_put_many_failure_stops_the_batch_and_reports_it() -> None: + backend = _FailingBackend() + store = Store(backend).limited(1) / "r" # one at a time, so the order is known + with pytest.raises(BatchError) as caught: + store.put_many([("ok", b"1"), ("bad", b"2"), ("later", b"3")]) + error = caught.value + assert [type(e) for e in error.exceptions] == [OSError] + assert [(key, type(result)) for key, result in error.completed] == [("ok", Written)] + assert error.remaining == ("bad", "later") + assert backend.attempted == ["r/ok", "r/bad"] + assert set(store.list()) == {"ok"} + + +def test_get_many_failure_raises_after_the_reads_before_it() -> None: + backend = _FailingBackend() + store = Store(backend).limited(1) / "r" # one at a time, so the order is known + store.put("ok", b"1") + backend.attempted.clear() + results = store.get_many(["ok", "bad", "later"]) + assert next(results)[0] == "ok" + with pytest.raises(BatchError) as caught: + next(results) + assert (caught.value.completed, caught.value.remaining) == ((), ("bad", "later")) + assert backend.attempted == ["r/ok", "r/bad"] + + +def _static_buffer_checks(host: Store[MemoryBackend], device: Store[_DeviceBackend]) -> None: + """Never run; pyright checks that each marked call is a type error.""" + host.get_into("k", bytearray(4)) + device.get_into("k", _DeviceBuffer(4)) + device.get_into("k", bytearray(4)) # pyright: ignore[reportArgumentType] + host.get_into("k", _DeviceBuffer(4)) # pyright: ignore[reportArgumentType] + Store(_ReadOnlyBackend({})).get_into("k", bytearray(4)) # pyright: ignore[reportAttributeAccessIssue] + device.get_into_many([("k", _DeviceBuffer(4))]) + device.get_into_many([("k", bytearray(4))]) # pyright: ignore[reportArgumentType] + host.get_into_many([("k", _DeviceBuffer(4), None)]) # pyright: ignore[reportArgumentType] + Store(_ReadOnlyBackend({})).put_many([("k", b"")]) # pyright: ignore[reportAttributeAccessIssue] + + +def test_store_over_unwritable_backend_is_read_only() -> None: + store = Store(_ReadOnlyBackend({})) + assert store.read_only + assert (store / "a").read_only + + +@pytest.mark.parametrize( + "make", + [ + lambda: RangeRequest(1.5, 3), # pyright: ignore[reportArgumentType] + lambda: RangeRequest(True, 3), + lambda: OffsetRequest("1"), # pyright: ignore[reportArgumentType] + lambda: SuffixRequest(2.0), # pyright: ignore[reportArgumentType] + ], + ids=["float", "bool", "str", "float-suffix"], +) +def test_byte_range_of_non_int_raises(make: object) -> None: + with pytest.raises(TypeError, match="must be an int"): + make() # pyright: ignore[reportCallIssue] + + +@pytest.mark.parametrize( + "make", + [ + lambda: RangeRequest(-1, 3), + lambda: RangeRequest(3, 1), + lambda: OffsetRequest(-1), + lambda: SuffixRequest(-1), + ], + ids=["negative-start", "end-before-start", "negative-offset", "negative-suffix"], +) +def test_byte_range_out_of_order_raises(make: object) -> None: + with pytest.raises(ValueError, match="<=|>="): + make() # pyright: ignore[reportCallIssue] + + +def test_store_is_not_value_equal() -> None: + backend = MemoryBackend() + assert Store(backend) != Store(backend) + + +@pytest.mark.parametrize("read_only", [False, True]) +@pytest.mark.parametrize("root", ["", "a/b"]) +def test_views_across_sync_and_async(root: str, read_only: bool) -> None: + """`as_async` and `as_sync` keep the backend, root and read-only flag, and don't own.""" + backend = MemoryBackend() + owner = Store(backend, read_only=read_only) + store = owner / root + async_view = store.as_async() + sync_view = async_view.as_sync() + for view in (async_view, sync_view): + assert (view.backend, view.root, view.read_only) == (backend, root, read_only) + assert view.shares_backend(store) + assert view.overlaps(store) + assert isinstance(async_view, AsyncStore) + assert isinstance(sync_view, Store) + asyncio.run(async_view.aclose()) + sync_view.close() + store.close() + assert not backend.closed + owner.close() + assert backend.closed + + +class _AsyncClosingBackend(MemoryBackend): + """A backend whose cleanup is a coroutine; records which close ran.""" + + def __init__(self) -> None: + super().__init__() + self.closed_by: list[str] = [] + + def close(self) -> None: + self.closed_by.append("close") + super().close() + + async def aclose(self) -> None: + self.closed_by.append("aclose") + super().close() + + +class _SyncClosingBackend(MemoryBackend): + def __init__(self) -> None: + super().__init__() + self.closed_by: list[str] = [] + + def close(self) -> None: + self.closed_by.append("close") + super().close() + + +async def _close_async(store: AsyncStore[_AsyncClosingBackend | _SyncClosingBackend]) -> None: + async with store: + pass + + +@pytest.mark.parametrize( + ("backend", "expected"), + [(_AsyncClosingBackend(), ["aclose"]), (_SyncClosingBackend(), ["close"])], + ids=["closable-async", "sync-close"], +) +def test_async_store_closes_its_backend( + backend: _AsyncClosingBackend | _SyncClosingBackend, expected: list[str] +) -> None: + """`AsyncStore` awaits a backend's `aclose` where it has one, and calls `close` otherwise.""" + asyncio.run(_close_async(AsyncStore(backend) / "derived")) + assert backend.closed_by == [] + asyncio.run(_close_async(AsyncStore(backend))) + assert backend.closed_by == expected + assert backend.closed + + +async def _static_surface_checks( + store: Store[MemoryBackend], astore: AsyncStore[MemoryBackend] +) -> None: + """Never run; pyright checks that each marked line is a type error.""" + store.get("k") + await astore.get("k") + store.get_async("k") # pyright: ignore[reportAttributeAccessIssue] + store.aclose() # pyright: ignore[reportAttributeAccessIssue] + astore.close() # pyright: ignore[reportAttributeAccessIssue] + await AsyncStore(_ReadOnlyBackend({})).get("k") # a sync backend serves async callers + await AsyncStore(_ReadOnlyBackend({})).put("k", b"") # pyright: ignore[reportAttributeAccessIssue] + + +def test_pickled_derived_views_do_not_own_the_backend() -> None: + """Pickled together, a store and its views share one restored backend, which only the store + closes, as before pickling.""" + store = Store(MemoryBackend()) + store2, view2, async2 = pickle.loads(pickle.dumps((store, store / "a", store.as_async()))) + view2.close() + asyncio.run(async2.aclose()) + assert not store2.backend.closed + store2.close() + assert store2.backend.closed + + +@pytest.mark.parametrize( + ("left", "right", "overlaps"), + [ + (Location(("s",), ""), Location(("s",), "a/b"), True), + (Location(("s",), "a"), Location(("s",), "a/b"), True), + (Location(("s",), "a/b"), Location(("s",), "a"), True), + (Location(("s",), "a"), Location(("s",), "a"), True), + (Location(("s",), "lat"), Location(("s",), "lat_bnds"), False), + (Location(("s",), "a"), Location(("s",), "b"), False), + (Location(("s",), ""), Location(("t",), ""), False), + ], +) +def test_location_overlaps(left: Location, right: Location, overlaps: bool) -> None: + assert left.overlaps(right) is overlaps + + +def test_memory_backends_are_locations_of_their_own() -> None: + """Two memory backends never see each other's keys; views of one always overlap.""" + a, b = Store(MemoryBackend()), Store(MemoryBackend()) + assert not a.overlaps(b) + assert (a / "x").overlaps(a) + assert (a / "x").location.path == "x" + + +def test_write_batch_checks_its_arguments_before_read_only() -> None: + """As single writes do: a bad key, or a key named twice, is reported before the refusal.""" + store = Store(MemoryBackend()).as_read_only() + with pytest.raises(InvalidKeyError): + store.put_many([("/bad", b"x")]) + with pytest.raises(InvalidKeyError): + store.delete_many(["/bad"]) + with pytest.raises(ValueError, match="more than once"): + store.put_many([("k", b"x"), ("k", b"y")]) + with pytest.raises(ReadOnlyError): + store.put_many([("k", b"x")]) + + +def test_store_over_an_unwritable_backend_says_why_it_is_read_only() -> None: + store = Store(_ReadOnlyBackend({})) + with pytest.raises(ReadOnlyError, match="backend can't write"): + store._writable_path("k") + + +@pytest.mark.parametrize("path", ["/a", "a/", "a//b", "./a", "a/../b"]) +def test_location_of_an_unnormalized_path_raises(path: str) -> None: + with pytest.raises(InvalidKeyError): + Location(("s",), path) + + +def test_shallow_copy_of_a_store_is_the_store() -> None: + """A shallow copy sharing the backend object would be a second owner; the store is immutable, + so the copy is the store itself.""" + store = Store(MemoryBackend()) + assert copy.copy(store) is store + assert copy.copy(store / "a").root == "a" diff --git a/packages/zarr-storage/uv.lock b/packages/zarr-storage/uv.lock index 3a026ad6ea..7c4c70262f 100644 --- a/packages/zarr-storage/uv.lock +++ b/packages/zarr-storage/uv.lock @@ -2863,6 +2863,9 @@ dependencies = [ ] [package.optional-dependencies] +obstore = [ + { name = "obstore" }, +] remote = [ { name = "fsspec" }, { name = "obstore" }, @@ -2901,12 +2904,13 @@ requires-dist = [ { name = "fsspec", marker = "extra == 'remote'", specifier = ">=2023.10.0" }, { name = "hypothesis", marker = "extra == 'testing'", specifier = ">=6.160" }, { name = "numpy", specifier = ">=2" }, + { name = "obstore", marker = "extra == 'obstore'", specifier = ">=0.12" }, { name = "obstore", marker = "extra == 'remote'", specifier = ">=0.5.1" }, { name = "packaging", specifier = ">=24.0" }, { name = "pytest", marker = "extra == 'testing'", specifier = ">=9" }, { name = "pytest-asyncio", marker = "extra == 'testing'", specifier = ">=1.0" }, ] -provides-extras = ["remote", "testing"] +provides-extras = ["obstore", "remote", "testing"] [package.metadata.requires-dev] docs = [ @@ -2922,7 +2926,7 @@ test = [ { name = "fsspec", specifier = ">=2023.10.0" }, { name = "hypothesis", specifier = ">=6.160" }, { name = "moto", extras = ["s3", "server"] }, - { name = "obstore", specifier = ">=0.5.1" }, + { name = "obstore", specifier = ">=0.12" }, { name = "pytest", specifier = ">=9" }, { name = "pytest-asyncio", specifier = ">=1.0" }, { name = "requests" }, From 599ed285ab1997870a911f7a59f58decd4c18820 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Thu, 3 Dec 2026 13:35:54 +0100 Subject: [PATCH 2/2] docs(zarr-storage): number the changelog fragment after the PR Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/changes/{0001.feature.md => 491.feature.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename packages/zarr-storage/changes/{0001.feature.md => 491.feature.md} (100%) diff --git a/packages/zarr-storage/changes/0001.feature.md b/packages/zarr-storage/changes/491.feature.md similarity index 100% rename from packages/zarr-storage/changes/0001.feature.md rename to packages/zarr-storage/changes/491.feature.md