From f04c70a0568ae51c6089e49e68bcafb9df28eaa4 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 17 Nov 2026 16:20:21 +0100 Subject: [PATCH 01/31] feat(zarr-storage): add a Zarr-agnostic storage package with a new store API Add `packages/zarr-storage`, a key-value storage layer that knows nothing about the Zarr spec. `DESIGN.md` is the contract. - `Store` is a view of a backend at a root: the one place that checks the key grammar, applies the root, and enforces read-only and closed states. `store / "a"` returns a view on the same backend; the constructed store owns the backend's lifecycle; there is no value equality (`shares_backend`, `overlaps` instead). - Prefix arguments name directories; `list_dir` yields `Key`, `Prefix` or `Entry`; `delete` removes one key and `delete_dir` a directory. - Reads return `None` for a missing key and take byte ranges (range, offset, suffix); `get_into` reads into a caller's buffer. Writes and deletes take `if_match` / `if_none_match` and report `applied=False` instead of raising. Every method has an `_async` twin. - Backends: `MemoryBackend`, `LocalBackend` (staged writes renamed into place under per-directory locks, unique nanosecond mtime stamps so generations don't repeat on filesystems that reuse inodes), and `ObjectStoreBackend` over obstore. - `zarr_storage.testing`: a conformance suite with capability mixins, run through both the sync and async methods, plus a Hypothesis state machine that checks random operations through random views against a model. Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-storage/CHANGELOG.md | 3 + packages/zarr-storage/DESIGN.md | 155 +++ packages/zarr-storage/LICENSE.txt | 21 + packages/zarr-storage/README.md | 3 + packages/zarr-storage/changes/README.md | 25 + packages/zarr-storage/justfile | 59 ++ packages/zarr-storage/pyproject.toml | 156 +++ .../zarr-storage/src/zarr_storage/__init__.py | 78 ++ .../src/zarr_storage/_byte_range.py | 38 + .../zarr-storage/src/zarr_storage/_errors.py | 44 + .../zarr-storage/src/zarr_storage/_keys.py | 71 ++ .../src/zarr_storage/_protocols.py | 142 +++ .../zarr-storage/src/zarr_storage/_store.py | 403 ++++++++ .../zarr-storage/src/zarr_storage/_types.py | 158 +++ .../src/zarr_storage/backends/__init__.py | 24 + .../src/zarr_storage/backends/_common.py | 38 + .../src/zarr_storage/backends/_local.py | 769 ++++++++++++++ .../src/zarr_storage/backends/_memory.py | 199 ++++ .../src/zarr_storage/backends/_obstore.py | 692 +++++++++++++ .../zarr-storage/src/zarr_storage/py.typed | 0 .../src/zarr_storage/testing/__init__.py | 40 + .../src/zarr_storage/testing/_api.py | 189 ++++ .../src/zarr_storage/testing/_stateful.py | 271 +++++ .../src/zarr_storage/testing/_suite.py | 964 ++++++++++++++++++ packages/zarr-storage/tests/__init__.py | 0 packages/zarr-storage/tests/test_local.py | 388 +++++++ packages/zarr-storage/tests/test_memory.py | 43 + packages/zarr-storage/tests/test_obstore.py | 176 ++++ packages/zarr-storage/tests/test_store.py | 117 +++ packages/zarr-storage/towncrier-template.md | 130 +++ packages/zarr-storage/uv.lock | 275 +++++ 31 files changed, 5671 insertions(+) create mode 100644 packages/zarr-storage/CHANGELOG.md create mode 100644 packages/zarr-storage/DESIGN.md create mode 100644 packages/zarr-storage/LICENSE.txt create mode 100644 packages/zarr-storage/README.md create mode 100644 packages/zarr-storage/changes/README.md create mode 100644 packages/zarr-storage/justfile create mode 100644 packages/zarr-storage/pyproject.toml create mode 100644 packages/zarr-storage/src/zarr_storage/__init__.py create mode 100644 packages/zarr-storage/src/zarr_storage/_byte_range.py create mode 100644 packages/zarr-storage/src/zarr_storage/_errors.py create mode 100644 packages/zarr-storage/src/zarr_storage/_keys.py create mode 100644 packages/zarr-storage/src/zarr_storage/_protocols.py create mode 100644 packages/zarr-storage/src/zarr_storage/_store.py create mode 100644 packages/zarr-storage/src/zarr_storage/_types.py create mode 100644 packages/zarr-storage/src/zarr_storage/backends/__init__.py create mode 100644 packages/zarr-storage/src/zarr_storage/backends/_common.py create mode 100644 packages/zarr-storage/src/zarr_storage/backends/_local.py create mode 100644 packages/zarr-storage/src/zarr_storage/backends/_memory.py create mode 100644 packages/zarr-storage/src/zarr_storage/backends/_obstore.py create mode 100644 packages/zarr-storage/src/zarr_storage/py.typed create mode 100644 packages/zarr-storage/src/zarr_storage/testing/__init__.py create mode 100644 packages/zarr-storage/src/zarr_storage/testing/_api.py create mode 100644 packages/zarr-storage/src/zarr_storage/testing/_stateful.py create mode 100644 packages/zarr-storage/src/zarr_storage/testing/_suite.py create mode 100644 packages/zarr-storage/tests/__init__.py create mode 100644 packages/zarr-storage/tests/test_local.py create mode 100644 packages/zarr-storage/tests/test_memory.py create mode 100644 packages/zarr-storage/tests/test_obstore.py create mode 100644 packages/zarr-storage/tests/test_store.py create mode 100644 packages/zarr-storage/towncrier-template.md create mode 100644 packages/zarr-storage/uv.lock diff --git a/packages/zarr-storage/CHANGELOG.md b/packages/zarr-storage/CHANGELOG.md new file mode 100644 index 0000000000..7c4bc92cad --- /dev/null +++ b/packages/zarr-storage/CHANGELOG.md @@ -0,0 +1,3 @@ +# Release notes + + diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md new file mode 100644 index 0000000000..c78c639127 --- /dev/null +++ b/packages/zarr-storage/DESIGN.md @@ -0,0 +1,155 @@ +# zarr-storage design (v0) + +Status: draft, 2026-11-17. This is the new storage API from the storage plan +(`proposals/store-hierarchy-layering.md` in the planning worktree). It is built in iterations; each +iteration ends with every backend passing the shared conformance suite. + +Sources, and what each contributed: + +- **zng_storage** (Davis Bennett's earlier prototype): 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. +- **zarr-python-planning store proposals**: `ReadResult`/`PutResult`/`ObjectMetadata`, conditional + writes that report `applied=False` instead of raising, the conformance-suite layout. +- **The storage plan**: 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 + ▲ +Store one concrete class: (backend, root, read_only, owner); validates keys, applies the root, + relativizes listings, enforces read-only; `store / "a"` is a view on the same backend +``` + +A **backend** is an object that implements some capability protocols (`Read`, `Write`, `List`, and their +async twins) on *backend paths*: `/`-separated strings, already joined with the root. Backends never +see relative keys and never join or strip paths. They hold everything that must exist once: the dict, +the filesystem root, a client, locks, concurrency limits. + +A **`Store`** is the only class users hold. It is a view: a backend plus a root. All key validation, +root joining, listing relativization and read-only enforcement happen in `Store`, 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). + +## 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 (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 (sync; each has an `_async` twin) + +| Method | Returns | Notes | +|---|---|---| +| `get(key, *, byte_range=None)` | `ReadResult \| None` | `None` when the key is missing (zarrs, TensorStore). Conditional reads (`if_not_match`) arrive with caching in iteration 3 | +| `get_ranges(key, ranges)` | `RangesResult \| None` | 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)` | `int \| None` | bytes written into `out`, any writable C-contiguous buffer; `ValueError` if it is too small, read-only or not contiguous | +| `head(key)` | `ObjectMetadata \| None` | size, generation, last-modified | +| `put(key, value, *, if_match=None, if_none_match=False)` | `PutResult` | `value` is any C-contiguous buffer, copied; a failed precondition returns `applied=False`, it doesn't raise; `KeyConflictError` where the backend can't hold a key and a directory with one name | +| `delete(key, *, if_match=None)` | `DeleteResult` | one key; deleting a directory name deletes nothing | +| `delete_dir(directory)` | `None` | everything under the directory | +| `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) | + +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). + +## Views, lifecycle, identity + +- `store / "a"` and `store.with_read_only(True)` return views on the same backend. A view of a + read-only store is read-only; `with_read_only(False)` on one raises `ReadOnlyError`. +- The store the user constructed owns the backend. `close()` on it closes the backend; on a derived + view it does nothing. After the backend closes, every view raises `StoreClosedError`. +- No value equality: `==` is identity. `shares_backend(other)` and `overlaps(other)` answer the questions + callers actually ask. +- 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 | Conditional `put` / `delete` | 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 / no | as the store does | as the store does | + +`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 in a key's place is that key's +file. 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, conditional writes raise `UnsupportedOperationError`. +`LocalBackend` doesn't sync to disk, and needs a root that doesn't span filesystems. + +`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, 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.testing.StoreSuite` holds the contract every backend meets; optional capabilities come +as mixins a backend's test class adds (`ConditionalPutSuite`, `KeyAndDirectorySuite`, +`PickleSuite`, ...) or their refusing counterparts (`NoConditionalPutSuite`, +`KeyDirectoryConflictSuite`, `ConditionalRaceSuite`, ...). Every test runs twice: through the sync +methods, and through the async methods on one event loop, so the two surfaces meet one contract. + +`StoreSuite.test_state_machine` drives random sequences of puts, conditional puts, deletes, +conditional deletes, `delete_dir` and listings through random views, and checks every step against a +dict model (`zarr_storage.testing._stateful.StoreMachine`), again through both surfaces. The obstore +tests also fail any async run that makes a blocking obstore call. + +## Configuration + +No global configuration. Every knob (local I/O concurrency) is a constructor parameter with its +default in the signature. + +## 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. + +## Iterations + +1. **Core:** types, `Store`, the memory and local backends, the conformance suite in + `zarr_storage.testing`, pickling. +2. **Remote and archive backends:** obstore (S3, GCS, Azure, HTTP; async-native), fsspec, zip. +3. **Composition:** range coalescing, 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/LICENSE.txt b/packages/zarr-storage/LICENSE.txt new file mode 100644 index 0000000000..1e8da4d242 --- /dev/null +++ b/packages/zarr-storage/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2025 Zarr Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/zarr-storage/README.md b/packages/zarr-storage/README.md new file mode 100644 index 0000000000..0843002d86 --- /dev/null +++ b/packages/zarr-storage/README.md @@ -0,0 +1,3 @@ +# zarr-storage + +A Zarr-agnostic key-value storage layer. Pre-alpha; see `DESIGN.md`. diff --git a/packages/zarr-storage/changes/README.md b/packages/zarr-storage/changes/README.md new file mode 100644 index 0000000000..6ea6eb1939 --- /dev/null +++ b/packages/zarr-storage/changes/README.md @@ -0,0 +1,25 @@ +Writing a changelog entry for `zarr-storage` +--------------------------------------------- + +Fragments in **this** directory are released notes for the `zarr-storage` +package only — kept separate from the parent zarr-python `changes/` +directory so a PR touching only `packages/zarr-storage/` produces a +release note for this package only. + +Please put a new file in this directory named `xxxx..md`, where + +- `xxxx` is the pull request number associated with this entry +- `` is one of: + - feature + - bugfix + - doc + - removal + - misc + +Inside the file, please write a short description of what you have +changed, and how it impacts users of `zarr-storage`. + +A `zarr-storage` release runs `towncrier build` in `packages/zarr-storage/`, +which consumes the fragments here and updates `CHANGELOG.md`. Fragments +that describe parent zarr-python changes (not the storage package) +belong in the top-level `changes/` directory, not here. diff --git a/packages/zarr-storage/justfile b/packages/zarr-storage/justfile new file mode 100644 index 0000000000..cafbf32765 --- /dev/null +++ b/packages/zarr-storage/justfile @@ -0,0 +1,59 @@ +# Development verbs for the zarr-storage package. Recipes run with this +# directory as the working directory regardless of where `just` is invoked. + +# List available recipes +# Quoted arguments must survive delegation from the root Justfile. +set positional-arguments + +default: + @just --list + +# Run the test suite on the project interpreter; extra args are passed to pytest +test *args: + uv run --group test pytest tests "$@" + +# The oldest and newest interpreters the package is declared for: the floor is +# `requires-python`, the ceiling the newest classifier, both read from +# pyproject.toml. CI's matrix is written out in its workflow, so a change to +# the declared range is made there too. +# uv fetches an interpreter it does not have. A difference in how a version +# materialises annotations or resolves a stub shows up here, not only in CI. +# Run the test suite on the oldest and newest supported interpreters +test-versions *args: + #!/usr/bin/env bash + set -euo pipefail + read -r floor ceiling < <(uv run python - <<'EOF' + import re + import tomllib + + project = tomllib.load(open("pyproject.toml", "rb"))["project"] + floor = re.fullmatch(r">=\s*(\d+\.\d+)", project["requires-python"]).group(1) + declared = [ + classifier.rsplit(" ", 1)[1] + for classifier in project["classifiers"] + if classifier.startswith("Programming Language :: Python :: 3.") + ] + print(floor, max(declared, key=lambda version: tuple(map(int, version.split("."))))) + EOF + ) + for version in "$floor" "$ceiling"; do + echo "== python $version ==" + uv run --python "$version" --group test pytest tests "$@" + done + +# Lint with the same invocation CI uses +lint: + uvx ruff check . + +# Run under the interpreter CI runs pyright under, so a version-dependent +# stdlib or stub difference shows up here rather than only in CI. +# Type-check the package, sources and tests alike +typecheck: + uv run --python 3.11 --group test --with pyright pyright + +# Run everything CI runs for this package, on both ends of the version range +check: lint typecheck test-versions + +# Preview the changelog that the next release would generate +changelog-draft: + uvx towncrier build --draft --version Unreleased diff --git a/packages/zarr-storage/pyproject.toml b/packages/zarr-storage/pyproject.toml new file mode 100644 index 0000000000..2ef3287654 --- /dev/null +++ b/packages/zarr-storage/pyproject.toml @@ -0,0 +1,156 @@ +[build-system] +requires = ["hatchling>=1.29.0", "hatch-vcs", "setuptools-scm>=9"] +build-backend = "hatchling.build" + +[project] +name = "zarr-storage" +dynamic = ["version"] +description = "A Zarr-agnostic key-value storage layer for Zarr implementations." +readme = "README.md" +requires-python = ">=3.11" +license = "MIT" +license-files = ["LICENSE.txt"] +authors = [ + { name = "Davis Bennett", email = "davis.v.bennett@gmail.com" }, +] +classifiers = [ + "Development Status :: 2 - Pre-Alpha", + "Intended Audience :: Developers", + "Intended Audience :: Information Technology", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Scientific/Engineering", + "Topic :: Software Development :: Libraries :: Python Modules", + "Typing :: Typed", +] +keywords = ["zarr", "storage", "key-value"] +dependencies = [ + # `typing_extensions.Buffer`, the buffer-protocol type, before Python 3.12's + # `collections.abc.Buffer`. + "typing_extensions>=4.6", +] + +[project.optional-dependencies] +# `zarr_storage.backends.ObjectStoreBackend`. +obstore = ["obstore>=0.12"] +# The `zarr_storage.testing` conformance suite. +testing = ["pytest>=8", "hypothesis>=6.85"] + +[project.urls] +Homepage = "https://github.com/zarr-developers/zarr-python" +Source = "https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-storage" +Issues = "https://github.com/zarr-developers/zarr-python/issues" +Changelog = "https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-storage/CHANGELOG.md" + +[dependency-groups] +test = [ + "pytest>=8", + "hypothesis>=6.85", + "obstore>=0.12", +] + +[tool.hatch.version] +source = "vcs" +tag-pattern = '^zarr_storage-v(?P.+)$' +raw-options = { root = "../..", scm = { git = { describe_command = "git describe --dirty --tags --long --match zarr_storage-v*" } }, local_scheme = "no-local-version", fallback_version = "0.0.0" } + +[tool.hatch.build.targets.wheel] +packages = ["src/zarr_storage"] + +# An allowlist, so nothing that merely happens to sit in the package directory +# can ride along in a release. +[tool.hatch.build.targets.sdist] +include = [ + "/src", + "/tests", + "/justfile", + "/CHANGELOG.md", +] + +[tool.ruff] +extend = "../../pyproject.toml" +target-version = "py311" + +[tool.ruff.lint] +# Use `object` for "any value"; a genuinely dynamic annotation needs a noqa +# saying why. +extend-select = ["ANN401"] + +[tool.pytest.ini_options] +minversion = "8" +testpaths = ["tests"] +xfail_strict = true +addopts = ["-ra", "--strict-config", "--strict-markers"] +filterwarnings = ["error"] + +[tool.numpydoc_validation] +checks = [ + "GL10", + "SS04", + "PR02", + "PR03", + "PR05", + "PR06", +] + +# Pyright is the only checker that runs on this package. +[tool.pyright] +include = ["src", "tests"] +enableTypeIgnoreComments = false +reportUnnecessaryTypeIgnoreComment = "error" +extraPaths = ["."] +typeCheckingMode = "strict" +pythonVersion = "3.11" + +[[tool.pyright.executionEnvironments]] +root = "tests" +reportMissingTypeArgument = false +reportPrivateUsage = false +reportUnknownArgumentType = false +reportUnknownLambdaType = false +reportUnknownMemberType = false +reportUnknownParameterType = false +reportUnknownVariableType = false +reportUnusedFunction = false + +[tool.towncrier] +directory = "changes" +filename = "CHANGELOG.md" +package = "zarr_storage" +underlines = ["", "", ""] +title_format = "## {version} ({project_date})" +issue_format = "[#{issue}](https://github.com/zarr-developers/zarr-python/pull/{issue})" +start_string = "\n" +template = "towncrier-template.md" + +[[tool.towncrier.type]] +directory = "feature" +name = "Features" +showcontent = true + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bugfixes" +showcontent = true + +[[tool.towncrier.type]] +directory = "doc" +name = "Improved Documentation" +showcontent = true + +[[tool.towncrier.type]] +directory = "removal" +name = "Deprecations and Removals" +showcontent = true + +[[tool.towncrier.type]] +directory = "misc" +name = "Misc" +showcontent = true diff --git a/packages/zarr-storage/src/zarr_storage/__init__.py b/packages/zarr-storage/src/zarr_storage/__init__.py new file mode 100644 index 0000000000..9bcbaf477a --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/__init__.py @@ -0,0 +1,78 @@ +"""A Zarr-agnostic key-value storage layer. + +A `Store` is a view of a backend at a root directory. Backends implement capability protocols +(`Readable`, `Writable`, `Listable`, and async twins) over backend paths; `Store` validates keys, +applies its root, enforces read-only access, and is the only object most callers need. +""" + +from zarr_storage._errors import ( + InvalidByteRangeError, + InvalidKeyError, + KeyConflictError, + ReadOnlyError, + StorageError, + StoreClosedError, + UnsupportedOperationError, +) +from zarr_storage._protocols import ( + Backend, + Listable, + ListableAsync, + Readable, + ReadableAsync, + ReadableInto, + ReadableIntoAsync, + Writable, + WritableAsync, +) +from zarr_storage._store import Store +from zarr_storage._types import ( + ByteRange, + DeleteResult, + Entry, + Generation, + Key, + ListItem, + ObjectMetadata, + OffsetRequest, + Prefix, + PutResult, + RangeRequest, + RangesResult, + ReadResult, + SuffixRequest, +) + +__all__ = [ + "Backend", + "ByteRange", + "DeleteResult", + "Entry", + "Generation", + "InvalidByteRangeError", + "InvalidKeyError", + "Key", + "KeyConflictError", + "ListItem", + "Listable", + "ListableAsync", + "ObjectMetadata", + "OffsetRequest", + "Prefix", + "PutResult", + "RangeRequest", + "RangesResult", + "ReadOnlyError", + "ReadResult", + "Readable", + "ReadableAsync", + "ReadableInto", + "ReadableIntoAsync", + "StorageError", + "Store", + "StoreClosedError", + "SuffixRequest", + "UnsupportedOperationError", + "Writable", + "WritableAsync", +] diff --git a/packages/zarr-storage/src/zarr_storage/_byte_range.py b/packages/zarr-storage/src/zarr_storage/_byte_range.py new file mode 100644 index 0000000000..5bc70c1705 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/_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._errors import InvalidByteRangeError +from zarr_storage._types import OffsetRequest, RangeRequest, SuffixRequest + +if TYPE_CHECKING: + from zarr_storage._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/_errors.py b/packages/zarr-storage/src/zarr_storage/_errors.py new file mode 100644 index 0000000000..9303456d4c --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/_errors.py @@ -0,0 +1,44 @@ +"""The errors a store raises. A missing key is not one of them: reads return `None`.""" + +from __future__ import annotations + +__all__ = [ + "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.""" diff --git a/packages/zarr-storage/src/zarr_storage/_keys.py b/packages/zarr-storage/src/zarr_storage/_keys.py new file mode 100644 index 0000000000..bbda939fda --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/_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._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/_protocols.py b/packages/zarr-storage/src/zarr_storage/_protocols.py new file mode 100644 index 0000000000..9f1db360a5 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/_protocols.py @@ -0,0 +1,142 @@ +"""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`'s methods are typed so that calling one the backend lacks is a +type error. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Protocol + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterator, Sequence + + from zarr_storage._types import ( + ByteRange, + DeleteResult, + Generation, + ListItem, + ObjectMetadata, + PutResult, + RangesResult, + ReadResult, + ) + +__all__ = [ + "Backend", + "Listable", + "ListableAsync", + "Readable", + "ReadableAsync", + "ReadableInto", + "ReadableIntoAsync", + "Writable", + "WritableAsync", +] + + +class Backend(Protocol): + """What every backend provides: a lifecycle and whether it accepts writes at all.""" + + @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.""" + ... + + +class Readable(Backend, Protocol): + def get(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: + """The value at `path`, or the requested part of it; `None` if the key is absent.""" + ... + + def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + """Several parts of the value at `path`, from one read; `None` if the key is absent.""" + ... + + def head(self, path: str) -> ObjectMetadata | None: + """The size and generation of the value at `path`; `None` if the key is absent.""" + ... + + +class ReadableInto(Backend, Protocol): + def get_into(self, path: str, out: memoryview, byte_range: ByteRange | None) -> int | None: + """Copy the value (or part) into `out`; the number of bytes, or `None` if absent. + + Raises `ValueError` if `out` is shorter than the bytes to copy. + """ + ... + + +class Writable(Backend, Protocol): + def put( + self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool + ) -> PutResult: + """Write `value` at `path`, if the preconditions hold.""" + ... + + def delete(self, path: str, *, if_match: Generation | None) -> DeleteResult: + """Delete the key at `path`, if the precondition holds. A directory is not a key.""" + ... + + def delete_dir(self, directory: str) -> None: + """Delete every key under `directory`.""" + ... + + +class Listable(Backend, Protocol): + 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.""" + ... + + +class ReadableAsync(Backend, Protocol): + async def get_async(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: ... + + async def get_ranges_async( + self, path: str, ranges: Sequence[ByteRange] + ) -> RangesResult | None: ... + + async def head_async(self, path: str) -> ObjectMetadata | None: ... + + +class ReadableIntoAsync(Backend, Protocol): + async def get_into_async( + self, path: str, out: memoryview, byte_range: ByteRange | None + ) -> int | None: ... + + +class WritableAsync(Backend, Protocol): + async def put_async( + self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool + ) -> PutResult: ... + + async def delete_async(self, path: str, *, if_match: Generation | None) -> DeleteResult: ... + + async def delete_dir_async(self, directory: str) -> None: ... + + +class ListableAsync(Backend, Protocol): + 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/_store.py b/packages/zarr-storage/src/zarr_storage/_store.py new file mode 100644 index 0000000000..489d130b32 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/_store.py @@ -0,0 +1,403 @@ +"""`Store`: a view of a backend at a root. + +`Store` is 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. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Final, Generic, Self, TypeVar, cast, final + +from typing_extensions import Buffer + +from zarr_storage._errors import ReadOnlyError, StoreClosedError +from zarr_storage._keys import check_key, is_within, join, normalize_directory, relativize +from zarr_storage._protocols import Backend + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterator, Sequence + from types import TracebackType + + from zarr_storage._protocols import ( + Listable, + ListableAsync, + Readable, + ReadableAsync, + ReadableInto, + ReadableIntoAsync, + Writable, + WritableAsync, + ) + from zarr_storage._types import ( + ByteRange, + DeleteResult, + Generation, + ListItem, + ObjectMetadata, + PutResult, + RangesResult, + ReadResult, + ) + +__all__ = ["Store"] + +B_co = TypeVar("B_co", bound=Backend, covariant=True) +T = TypeVar("T") + + +def _as_bytes_view(value: Buffer, *, writable: bool) -> memoryview: + """A flat, C-contiguous byte view of a buffer.""" + 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 + + +@final +class Store(Generic[B_co]): + """A backend seen from a root directory. + + Construct a store from a backend; the store you construct owns the backend and closes it. + `store / "a"` and `with_read_only()` 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. + + `backend` gives direct access to the backend, which bypasses the key grammar, the root, and + read-only and closed checks. + + Stores have no value equality: `==` is identity. Use `shares_backend` and `overlaps` to compare + stores. + + Parameters + ---------- + backend + The backend to read and write through. + root + The directory within the backend that this store's keys are relative to. + read_only + Refuse writes through this store. A backend that can't write makes every store over it + read-only. + """ + + __slots__ = ("_backend", "_owner", "_read_only", "_root") + + def __init__(self, backend: B_co, *, root: str = "", read_only: bool = False) -> None: + self._backend: Final[B_co] = backend + self._root: Final[str] = normalize_directory(root) + self._read_only: Final[bool] = read_only or not backend.writable + self._owner = True + + # ----------------------------------------------------------------- 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 closed(self) -> bool: + """Whether the backend has been closed.""" + return self._backend.closed + + def _view(self, *, root: str, read_only: bool) -> Self: + view = type(self)(self._backend, root=root, read_only=read_only) + view._owner = False + return view + + 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 + ) + + def with_read_only(self, read_only: bool = True) -> Self: + """A view on the same backend and root that refuses writes, or accepts them. + + A read-only store can't produce a writable view: `with_read_only(False)` on one raises + `ReadOnlyError`. + """ + if self._read_only and not read_only: + raise ReadOnlyError(f"{self!r} is read-only; its views are read-only too.") + return self._view(root=self._root, read_only=read_only) + + def shares_backend(self, other: Store[Backend]) -> bool: + """Whether `other` reads and writes through the same backend object.""" + return self._backend is other._backend + + def overlaps(self, other: Store[Backend]) -> bool: + """Whether a key could be visible through both stores: same backend, nested roots.""" + return self.shares_backend(other) and ( + is_within(self._root, other._root) or is_within(other._root, self._root) + ) + + 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 (_restore_store, (type(self), self._backend, self._root, self._read_only)) + + # ----------------------------------------------------------------- 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() + + # ----------------------------------------------------------------- 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 _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 + + async def _open_items_async(self, items: AsyncIterator[T]) -> AsyncIterator[T]: + async for item in items: + self._check_open() + yield item + + def _writable_path(self, key: str) -> str: + path = self._path(key) + if self._read_only: + raise ReadOnlyError(f"{self!r} is read-only.") + return path + + def _writable_directory(self, directory: str) -> str: + path = self._directory(directory) + if self._read_only: + raise ReadOnlyError(f"{self!r} is read-only.") + return path + + # ----------------------------------------------------------------- sync reads + + def get( + self: Store[Readable], key: str, *, byte_range: ByteRange | None = None + ) -> ReadResult | None: + """The value at `key`, or the part `byte_range` selects; `None` if the key is absent.""" + return self._backend.get(self._path(key), byte_range) + + def get_ranges( + self: Store[Readable], key: str, ranges: Sequence[ByteRange] + ) -> RangesResult | None: + """Several parts of the value at `key` from one read; `None` if the key is absent.""" + return self._backend.get_ranges(self._path(key), ranges) + + def get_into( + self: Store[Readable], + key: str, + out: Buffer, + *, + byte_range: ByteRange | None = None, + ) -> int | None: + """Copy the value at `key` (or part of it) into `out`. + + Returns the number of bytes copied, or `None` if the key is absent. Raises `ValueError` if + `out` is shorter than the bytes to copy, read-only, or not C-contiguous. + """ + path = self._path(key) + view = _as_bytes_view(out, writable=True) + if hasattr(self._backend, "get_into"): + return cast("ReadableInto", self._backend).get_into(path, view, byte_range) + result = self._backend.get(path, byte_range) + if result is None: + return None + return _copy_into(result.value, view) + + def head(self: Store[Readable], key: str) -> ObjectMetadata | None: + """The size and generation of the value at `key`; `None` if the key is absent.""" + return self._backend.head(self._path(key)) + + def exists(self: Store[Readable], key: str) -> bool: + """Whether `key` holds a value.""" + return self.head(key) is not None + + # ----------------------------------------------------------------- sync writes + + def put( + self: Store[Writable], + key: str, + value: Buffer, + *, + if_match: Generation | None = None, + if_none_match: bool = False, + ) -> PutResult: + """Write `value` at `key`. + + With `if_match`, write only if the key's current generation equals it. With + `if_none_match`, write only if the key is absent. A failed precondition returns + `PutResult(applied=False)`; it does not raise. + """ + if if_match is not None and if_none_match: + raise ValueError("Pass at most one of if_match and if_none_match.") + path = self._writable_path(key) + return self._backend.put( + path, + _as_bytes_view(value, writable=False), + if_match=if_match, + if_none_match=if_none_match, + ) + + def delete( + self: Store[Writable], key: str, *, if_match: Generation | None = None + ) -> DeleteResult: + """Delete the key `key`. A directory is not a key: deleting one deletes nothing.""" + return self._backend.delete(self._writable_path(key), if_match=if_match) + + def delete_dir(self: Store[Writable], directory: str = "") -> None: + """Delete every key under `directory` (by default, every key in this store).""" + self._backend.delete_dir(self._writable_directory(directory)) + + # ----------------------------------------------------------------- sync listing + + 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`. + """ + 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))) + + # ----------------------------------------------------------------- async reads + + async def get_async( + self: Store[ReadableAsync], key: str, *, byte_range: ByteRange | None = None + ) -> ReadResult | None: + """Async `get`.""" + return await self._backend.get_async(self._path(key), byte_range) + + async def get_ranges_async( + self: Store[ReadableAsync], key: str, ranges: Sequence[ByteRange] + ) -> RangesResult | None: + """Async `get_ranges`.""" + return await self._backend.get_ranges_async(self._path(key), ranges) + + async def get_into_async( + self: Store[ReadableAsync], + key: str, + out: Buffer, + *, + byte_range: ByteRange | None = None, + ) -> int | None: + """Async `get_into`.""" + path = self._path(key) + view = _as_bytes_view(out, writable=True) + if hasattr(self._backend, "get_into_async"): + backend = cast("ReadableIntoAsync", self._backend) + return await backend.get_into_async(path, view, byte_range) + result = await self._backend.get_async(path, byte_range) + if result is None: + return None + return _copy_into(result.value, view) + + async def head_async(self: Store[ReadableAsync], key: str) -> ObjectMetadata | None: + """Async `head`.""" + return await self._backend.head_async(self._path(key)) + + async def exists_async(self: Store[ReadableAsync], key: str) -> bool: + """Async `exists`.""" + return await self.head_async(key) is not None + + # ----------------------------------------------------------------- async writes + + async def put_async( + self: Store[WritableAsync], + key: str, + value: Buffer, + *, + if_match: Generation | None = None, + if_none_match: bool = False, + ) -> PutResult: + """Async `put`.""" + if if_match is not None and if_none_match: + raise ValueError("Pass at most one of if_match and if_none_match.") + path = self._writable_path(key) + return await self._backend.put_async( + path, + _as_bytes_view(value, writable=False), + if_match=if_match, + if_none_match=if_none_match, + ) + + async def delete_async( + self: Store[WritableAsync], key: str, *, if_match: Generation | None = None + ) -> DeleteResult: + """Async `delete`.""" + return await self._backend.delete_async(self._writable_path(key), if_match=if_match) + + async def delete_dir_async(self: Store[WritableAsync], directory: str = "") -> None: + """Async `delete_dir`.""" + await self._backend.delete_dir_async(self._writable_directory(directory)) + + # ----------------------------------------------------------------- async listing + + def list_async(self: Store[ListableAsync], directory: str = "") -> AsyncIterator[str]: + """Async `list`.""" + paths = self._backend.list_async(self._directory(directory)) + return self._open_items_async(_relativized(paths, self._root)) + + def list_dir_async(self: Store[ListableAsync], directory: str = "") -> AsyncIterator[ListItem]: + """Async `list_dir`.""" + return self._open_items_async(self._backend.list_dir_async(self._directory(directory))) + + +async def _relativized(paths: AsyncIterator[str], root: str) -> AsyncIterator[str]: + async for path in paths: + yield relativize(path, root) + + +def _copy_into(value: memoryview, out: memoryview) -> int: + 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 n + + +def _restore_store( + cls: type[Store[Backend]], backend: Backend, root: str, read_only: bool +) -> Store[Backend]: + return cls(backend, root=root, read_only=read_only) diff --git a/packages/zarr-storage/src/zarr_storage/_types.py b/packages/zarr-storage/src/zarr_storage/_types.py new file mode 100644 index 0000000000..c527e8e77a --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/_types.py @@ -0,0 +1,158 @@ +"""Values that stores take and return. All are immutable.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import NewType + +__all__ = [ + "ByteRange", + "DeleteResult", + "Entry", + "Generation", + "Key", + "ListItem", + "ObjectMetadata", + "OffsetRequest", + "Prefix", + "PutResult", + "RangeRequest", + "RangesResult", + "ReadResult", + "SuffixRequest", +] + +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. +""" + + +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 ReadResult: + """The bytes a read returned, and the generation they belong to.""" + + value: memoryview + generation: Generation + + +@dataclass(frozen=True, slots=True) +class RangesResult: + """The bytes of several ranges of one value, all from one read of one generation.""" + + values: tuple[memoryview, ...] + generation: Generation + + +@dataclass(frozen=True, slots=True) +class PutResult: + """The outcome of a write. + + `applied` is `False` when a precondition (`if_match`, `if_none_match`) failed; `generation` is + then the key's current generation, or `None` if the key is absent. When `applied` is `True`, + `generation` is the generation of the value just written. + """ + + generation: Generation | None + applied: bool = True + + +@dataclass(frozen=True, slots=True) +class DeleteResult: + """The outcome of a delete. + + | case | `generation` | `applied` | + |---|---|---| + | the key was absent | `None` | `False` | + | `if_match` did not match | the current generation | `False` | + | the key was deleted | the generation of the deleted value | `True` | + """ + + generation: Generation | None + applied: bool + + +@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/backends/__init__.py b/packages/zarr-storage/src/zarr_storage/backends/__init__.py new file mode 100644 index 0000000000..d0dd4b42ec --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/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.backends._local import LocalBackend +from zarr_storage.backends._memory import MemoryBackend + +if TYPE_CHECKING: + from zarr_storage.backends._obstore import ObjectStoreBackend + +__all__ = ["LocalBackend", "MemoryBackend", "ObjectStoreBackend"] + + +def __getattr__(name: str) -> object: + if name == "ObjectStoreBackend": + from zarr_storage.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/backends/_common.py b/packages/zarr-storage/src/zarr_storage/backends/_common.py new file mode 100644 index 0000000000..b6d63190e3 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/backends/_common.py @@ -0,0 +1,38 @@ +"""Helpers shared by backends that hold a flat set of keys.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from zarr_storage._keys import is_within, relativize +from zarr_storage._types import Key, Prefix + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + + from zarr_storage._types import ListItem + +__all__ = ["children", "strictly_within"] + + +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/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py new file mode 100644 index 0000000000..08f08dee2f --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -0,0 +1,769 @@ +"""A backend over a directory on the local filesystem.""" + +from __future__ import annotations + +import asyncio +import contextlib +import errno +import os +import shutil +import stat +import sys +import threading +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from functools import partial +from pathlib import Path +from typing import TYPE_CHECKING, ParamSpec, TypedDict, TypeVar + +from zarr_storage._byte_range import resolve +from zarr_storage._errors import ( + InvalidKeyError, + KeyConflictError, + StoreClosedError, + UnsupportedOperationError, +) +from zarr_storage._types import ( + DeleteResult, + Generation, + Key, + ObjectMetadata, + Prefix, + PutResult, + RangesResult, + ReadResult, +) + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Callable, Generator, Iterator, Sequence + from io import BufferedReader + + from zarr_storage._types import ByteRange, ListItem + +__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)) + +P = ParamSpec("P") +T = TypeVar("T") + + +class _State(TypedDict): + root: str + concurrency: int + closed: bool + + +class _Retry(Exception): + """A concurrent `delete_dir` removed a directory a write was using; start the write over.""" + + +_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 segment.endswith(RESERVED_SUFFIX): + return f"names ending in {RESERVED_SUFFIX!r} 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 _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 a directory.""" + try: + return open(file, "rb") + except (FileNotFoundError, IsADirectoryError, NotADirectoryError): + return None + except PermissionError: + # Windows refuses to open a directory with PermissionError. + if file.is_dir(): + return None + raise + + +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) -> 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. + + Raises `_Retry` if the directory is being removed. + """ + lock_path = directory / _LOCK_NAME + while True: + try: + fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o644) + 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) + 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, + if_match: Generation | None, + if_none_match: bool, +) -> PutResult: + """Rename `temp` to `file` if the preconditions hold. 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) + current = None if st is None else _generation(st) + if (if_none_match and current is not None) or (if_match is not None and if_match != current): + return PutResult(current, applied=False) + 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 PutResult(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(directory: Path, *, remove_self: bool) -> None: + """Delete every key under `directory`, and its subdirectories, each under its own lock. + + 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 entry.name.endswith(RESERVED_SUFFIX): + # 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 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 or Unicode-normalizing filesystems (the + defaults on macOS and Windows), keys that differ only in case or normalization are the same key. + + Parameters + ---------- + root + The directory that holds the keys. + create + Create `root` if it doesn't exist. With `create=False`, a missing root raises + `FileNotFoundError`. + concurrency + The number of threads that run the async methods' file operations. + """ + + def __init__( + self, root: str | os.PathLike[str], *, create: bool = True, concurrency: int = 16 + ) -> None: + if concurrency < 1: + raise ValueError(f"concurrency must be >= 1; got {concurrency}.") + self._root = Path(root).resolve() + if create: + self._root.mkdir(parents=True, exist_ok=True) + elif not self._root.is_dir(): + raise FileNotFoundError(f"The root directory {str(self._root)!r} does not exist.") + self._concurrency = concurrency + self._executor: ThreadPoolExecutor | None = None + self._executor_lock = threading.Lock() + self._probe_lock = threading.Lock() + self._exact_times: bool | None = None + self._closed = False + + @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), "concurrency": self._concurrency, "closed": self._closed} + + def __setstate__(self, state: _State) -> None: + self._root = Path(state["root"]) + self._concurrency = state["concurrency"] + self._executor = None + self._executor_lock = threading.Lock() + self._probe_lock = threading.Lock() + self._exact_times = None + self._closed = state["closed"] + + # --- Backend + + @property + def closed(self) -> bool: + return self._closed + + @property + def writable(self) -> bool: + return True + + def close(self) -> None: + with self._executor_lock: + self._closed = True + executor, self._executor = self._executor, None + if executor is not None: + executor.shutdown(wait=True) + + # --- paths + + def _file(self, path: str) -> Path: + _check_segments(path) + return self._root / path + + def _directory(self, directory: str) -> Path: + if directory == "": + return self._root + _check_segments(directory) + return self._root / directory + + # --- Readable + + def get(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: + with _key_errors(path): + f = _open_key(self._file(path)) + if f is None: + return None + with f: + st = os.fstat(f.fileno()) + start, end = resolve(byte_range, st.st_size) + f.seek(start) + data = f.read(end - start) + return ReadResult(memoryview(data), _generation(st)) + + def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + with _key_errors(path): + f = _open_key(self._file(path)) + if f is None: + return None + 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 RangesResult(tuple(parts), _generation(st)) + + def get_into(self, path: str, out: memoryview, byte_range: ByteRange | None) -> int | None: + with _key_errors(path): + f = _open_key(self._file(path)) + if f is None: + return None + with f: + st = os.fstat(f.fileno()) + start, end = resolve(byte_range, st.st_size) + n = end - start + if n > len(out): + raise ValueError(f"The output buffer holds {len(out)} bytes; the value has {n}.") + f.seek(start) + _read_exact_into(f, out[:n]) + return n + + def head(self, path: str) -> ObjectMetadata | None: + with _key_errors(path): + st = _stat_key(self._file(path)) + if st is None: + return None + return ObjectMetadata(st.st_size, _generation(st), st.st_mtime) + + # --- Writable + + def put( + self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool + ) -> PutResult: + file = self._file(path) + if if_match is not None or if_none_match: + self._require_exact_times() + 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, if_match, if_none_match) + 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: + f.write(value) + f.flush() + _set_mtime(f.fileno(), temp, _unique_stamp()) + staged = _generation(os.fstat(f.fileno())) + 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 directory between the root and `file` is a regular file (a key).""" + parent = file.parent + while parent != self._root: + if _stat_key(parent) is not None: + return True + parent = parent.parent + return False + + def _commit( + self, + file: Path, + path: str, + temp: Path, + staged: Generation, + if_match: Generation | None, + if_none_match: bool, + ) -> PutResult: + """Rename `temp` to `file` if the preconditions hold, 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, 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, if_match, if_none_match) + + def delete(self, path: str, *, if_match: Generation | None) -> DeleteResult: + file = self._file(path) + if if_match is not None: + self._require_exact_times() + with _key_errors(path): + try: + with _directory_lock(file.parent): + st = _stat_key(file) + if st is None: + return DeleteResult(None, applied=False) + current = _generation(st) + if if_match is not None and if_match != current: + return DeleteResult(current, applied=False) + file.unlink() + except (_Retry, NotADirectoryError): + # The key's directory doesn't exist, or a parent is a key: the key is absent. + return DeleteResult(None, applied=False) + return DeleteResult(current, applied=True) + + def delete_dir(self, directory: str) -> None: + target = self._directory(directory) + with _key_errors(directory): + if target == self._root: + _remove_tree(self._root, remove_self=False) + elif target.is_dir() and not target.is_symlink(): + _remove_tree(target, remove_self=True) + + # --- Listable + + def list(self, directory: str) -> Iterator[str]: + target = self._directory(directory) + prefix = "" if directory == "" else f"{directory}/" + with _key_errors(directory): + return iter(list(_walk(target, prefix))) + + def list_dir(self, directory: str) -> Iterator[ListItem]: + target = self._directory(directory) + with _key_errors(directory): + try: + entries = list(os.scandir(target)) + except (FileNotFoundError, NotADirectoryError): + return iter(()) + return _classify(entries) + + # --- async twins: run the sync methods on the backend's threads + + def _pool(self) -> ThreadPoolExecutor: + with self._executor_lock: + if self._closed: + raise StoreClosedError(f"{self!r} is closed.") + if self._executor is None: + self._executor = ThreadPoolExecutor( + max_workers=self._concurrency, thread_name_prefix="zarr-storage-local" + ) + return self._executor + + async def _run(self, fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: + loop = asyncio.get_running_loop() + return await loop.run_in_executor(self._pool(), partial(fn, *args, **kwargs)) + + async def get_async(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: + return await self._run(self.get, path, byte_range) + + async def get_ranges_async(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + return await self._run(self.get_ranges, path, ranges) + + async def head_async(self, path: str) -> ObjectMetadata | None: + return await self._run(self.head, path) + + async def get_into_async( + self, path: str, out: memoryview, byte_range: ByteRange | None + ) -> int | None: + return await self._run(self.get_into, path, out, byte_range) + + async def put_async( + self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool + ) -> PutResult: + return await self._run( + self.put, path, value, if_match=if_match, if_none_match=if_none_match + ) + + async def delete_async(self, path: str, *, if_match: Generation | None) -> DeleteResult: + return await self._run(self.delete, path, if_match=if_match) + + async def delete_dir_async(self, directory: str) -> None: + await self._run(self.delete_dir, directory) + + async def list_async(self, directory: str) -> AsyncIterator[str]: + for path in await self._run(_materialize, self.list(directory)): + yield path + + async def list_dir_async(self, directory: str) -> AsyncIterator[ListItem]: + for item in await self._run(_materialize, self.list_dir(directory)): + yield item + + +def _materialize(items: Iterator[T]) -> list[T]: + return list(items) + + +def _walk(directory: Path, prefix: str) -> Iterator[str]: + try: + entries = list(os.scandir(directory)) + except (FileNotFoundError, NotADirectoryError): + return + for entry in entries: + if entry.name.endswith(RESERVED_SUFFIX): + continue + if entry.is_dir(follow_symlinks=False): + yield from _walk(Path(entry.path), f"{prefix}{entry.name}/") + else: + yield f"{prefix}{entry.name}" + + +def _classify(entries: list[os.DirEntry[str]]) -> Iterator[ListItem]: + for entry in entries: + if entry.name.endswith(RESERVED_SUFFIX): + continue + if entry.is_dir(follow_symlinks=False): + yield Prefix(entry.name) + else: + yield Key(entry.name) + + +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/backends/_memory.py b/packages/zarr-storage/src/zarr_storage/backends/_memory.py new file mode 100644 index 0000000000..e474cdd365 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/backends/_memory.py @@ -0,0 +1,199 @@ +"""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 + +from zarr_storage._byte_range import resolve +from zarr_storage._types import ( + DeleteResult, + Generation, + ObjectMetadata, + PutResult, + RangesResult, + ReadResult, +) +from zarr_storage.backends._common import children, strictly_within + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterator, Sequence + + from zarr_storage._types import ByteRange, ListItem + +__all__ = ["MemoryBackend"] + + +@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 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) -> ReadResult | None: + value = self._values.get(path) + if value is None: + return None + start, end = resolve(byte_range, len(value.data)) + return ReadResult(memoryview(value.data)[start:end], Generation(value.generation)) + + def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + value = self._values.get(path) + if value is None: + return None + view = memoryview(value.data) + size = len(value.data) + parts = tuple(view[slice(*resolve(r, size))] for r in ranges) + return RangesResult(parts, Generation(value.generation)) + + def head(self, path: str) -> ObjectMetadata | None: + value = self._values.get(path) + if value is None: + return None + return ObjectMetadata(len(value.data), Generation(value.generation), value.last_modified) + + def get_into(self, path: str, out: memoryview, byte_range: ByteRange | None) -> int | None: + value = self._values.get(path) + if value is None: + return None + start, end = resolve(byte_range, len(value.data)) + n = end - start + if n > len(out): + raise ValueError(f"The output buffer holds {len(out)} bytes; the value has {n}.") + out[:n] = memoryview(value.data)[start:end] + return n + + # --- Writable + + def put( + self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool + ) -> PutResult: + data = bytes(value) + with self._lock: + current = self._values.get(path) + current_generation = None if current is None else Generation(current.generation) + if if_none_match and current is not None: + return PutResult(current_generation, applied=False) + if if_match is not None and if_match != current_generation: + return PutResult(current_generation, applied=False) + generation = self._next_generation + self._next_generation += 1 + self._values[path] = _Value(data, generation, time.time()) + return PutResult(Generation(generation)) + + def delete(self, path: str, *, if_match: Generation | None) -> DeleteResult: + with self._lock: + current = self._values.get(path) + if current is None: + return DeleteResult(None, applied=False) + current_generation = Generation(current.generation) + if if_match is not None and if_match != current_generation: + return DeleteResult(current_generation, applied=False) + del self._values[path] + return DeleteResult(current_generation, applied=True) + + 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) -> ReadResult | None: + return self.get(path, byte_range) + + async def get_ranges_async(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + return self.get_ranges(path, ranges) + + async def head_async(self, path: str) -> ObjectMetadata | None: + return self.head(path) + + async def get_into_async( + self, path: str, out: memoryview, byte_range: ByteRange | None + ) -> int | None: + return self.get_into(path, out, byte_range) + + async def put_async( + self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool + ) -> PutResult: + return self.put(path, value, if_match=if_match, if_none_match=if_none_match) + + async def delete_async(self, path: str, *, if_match: Generation | None) -> DeleteResult: + return self.delete(path, if_match=if_match) + + 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/backends/_obstore.py b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py new file mode 100644 index 0000000000..ee038de086 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py @@ -0,0 +1,692 @@ +"""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 +from pathlib import Path +from typing import TYPE_CHECKING, cast + +import obstore +from obstore.exceptions import AlreadyExistsError, GenericError, PreconditionError +from obstore.store import HTTPStore, LocalStore + +from zarr_storage._byte_range import resolve +from zarr_storage._errors import InvalidKeyError, KeyConflictError, UnsupportedOperationError +from zarr_storage._keys import check_key, relativize +from zarr_storage._types import ( + DeleteResult, + Generation, + Key, + ObjectMetadata, + OffsetRequest, + Prefix, + PutResult, + RangeRequest, + RangesResult, + ReadResult, + SuffixRequest, +) + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Iterable, Iterator, Sequence + + from obstore import GetOptions, ListResult, ListStream, ObjectMeta, PutMode + from obstore.store import ObjectStore + + from zarr_storage._types import ByteRange, ListItem + +__all__ = ["ObjectStoreBackend"] + +_EMPTY = memoryview(b"") + + +# ---------------------------------------------------------------------------- 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 + + +class _NeverMatches: + """The precondition names a generation this backend did not mint, so no stored value has it.""" + + +_NEVER_MATCHES = _NeverMatches() + + +def _put_mode(if_match: Generation | None, if_none_match: bool) -> PutMode | _NeverMatches | None: + if if_none_match: + return "create" + if if_match is None: + return None + version = _version_of(if_match) + if version is None: + return _NEVER_MATCHES + 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) + + +# ---------------------------------------------------------------------------- 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 | None, byte_range: ByteRange | None, error: BaseException | None +) -> ReadResult | None: + """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 meta is None: + return None + start, end = resolve(byte_range, meta.size) + if start == end: + return ReadResult(_EMPTY, meta.generation) + 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. Conditional writes need a store that supports them + (S3, GCS, Azure and obstore's `MemoryStore` do; obstore's `LocalStore` supports only + `if_none_match`); otherwise they raise `UnsupportedOperationError`. Conditional deletes are not + supported. + + `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._closed = False + + @property + def store(self) -> ObjectStore: + """The obstore store.""" + return self._store + + def __repr__(self) -> str: + return f"ObjectStoreBackend({self._store!r})" + + # --- Backend + + @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 _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 | None: + try: + return _metadata(obstore.head(self._store, path)) + except FileNotFoundError: + return None + except GenericError: + if self._under_a_key(path): + return None + raise + + async def head_async(self, path: str) -> ObjectMetadata | None: + try: + return _metadata(await obstore.head_async(self._store, path)) + except FileNotFoundError: + return None + except GenericError: + if await self._under_a_key_async(path): + return None + raise + + def get(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: + 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=_get_options(byte_range)) + except FileNotFoundError: + return None + except GenericError as e: + return _empty_read_or_raise(self.head(path), byte_range, e) + meta = result.meta + return ReadResult(memoryview(result.bytes()), _generation(meta["e_tag"], meta["version"])) + + async def get_async(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: + 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=_get_options(byte_range)) + except FileNotFoundError: + return None + except GenericError as e: + return _empty_read_or_raise(await self.head_async(path), byte_range, e) + meta = result.meta + data = await result.bytes_async() + return ReadResult(memoryview(data), _generation(meta["e_tag"], meta["version"])) + + def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + 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 None + 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 RangesResult((memoryview(first.bytes()), *rest), generation) + + 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]) -> RangesResult | None: + try: + result = obstore.get(self._store, path) + except FileNotFoundError: + return None + except GenericError: + if self._under_a_key(path): + return None + raise + generation = _generation(result.meta["e_tag"], result.meta["version"]) + return RangesResult(_slices(memoryview(result.bytes()), ranges), generation) + + async def get_ranges_async(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + 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 None + 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 RangesResult((memoryview(await first.bytes_async()), *rest), generation) + + async def _read_whole_and_slice_async( + self, path: str, ranges: Sequence[ByteRange] + ) -> RangesResult | None: + try: + result = await obstore.get_async(self._store, path) + except FileNotFoundError: + return None + except GenericError: + if await self._under_a_key_async(path): + return None + raise + generation = _generation(result.meta["e_tag"], result.meta["version"]) + return RangesResult(_slices(memoryview(await result.bytes_async()), ranges), generation) + + # --- Writable + + def put( + self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool + ) -> PutResult: + mode = _put_mode(if_match, if_none_match) + if isinstance(mode, _NeverMatches): + return PutResult(_generation_or_none(self.head(path)), applied=False) + 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 current is None and self._reclaim_empty_directory(path): + return self.put(path, value, if_match=if_match, if_none_match=if_none_match) + if current is None and self._conflicts(path): + raise _conflict(path, self._store) from None + return PutResult(_generation_or_none(current), applied=False) + 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): + return self.put(path, value, if_match=if_match, if_none_match=if_none_match) + if self._conflicts(path) or self._is_directory(path): + raise _conflict(path, self._store) from e + raise + return PutResult(_generation(result["e_tag"], result["version"])) + + async def put_async( + self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool + ) -> PutResult: + mode = _put_mode(if_match, if_none_match) + if isinstance(mode, _NeverMatches): + return PutResult(_generation_or_none(await self.head_async(path)), applied=False) + try: + result = await obstore.put_async(self._store, path, bytes(value), mode=mode) + except (AlreadyExistsError, PreconditionError): + current = await self.head_async(path) + if current is None and await asyncio.to_thread(self._reclaim_empty_directory, path): + return await self.put_async( + path, value, if_match=if_match, if_none_match=if_none_match + ) + if current is None and await self._conflicts_async(path): + raise _conflict(path, self._store) from None + return PutResult(_generation_or_none(current), applied=False) + 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): + return await self.put_async( + path, value, if_match=if_match, if_none_match=if_none_match + ) + if await self._conflicts_async(path) or await asyncio.to_thread( + self._is_directory, path + ): + raise _conflict(path, self._store) from e + raise + return PutResult(_generation(result["e_tag"], result["version"])) + + def delete(self, path: str, *, if_match: Generation | None) -> DeleteResult: + _refuse_conditional_delete(if_match) + meta = self.head(path) + if meta is None: + return DeleteResult(None, applied=False) + try: + obstore.delete(self._store, path) + except FileNotFoundError: + return DeleteResult(None, applied=False) + return DeleteResult(meta.generation, applied=True) + + async def delete_async(self, path: str, *, if_match: Generation | None) -> DeleteResult: + _refuse_conditional_delete(if_match) + meta = await self.head_async(path) + if meta is None: + return DeleteResult(None, applied=False) + try: + await obstore.delete_async(self._store, path) + except FileNotFoundError: + return DeleteResult(None, applied=False) + return DeleteResult(meta.generation, applied=True) + + 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 _generation_or_none(meta: ObjectMetadata | None) -> Generation | None: + return None if meta is None else meta.generation + + +def _refuse_conditional_delete(if_match: Generation | None) -> None: + if if_match is not None: + raise UnsupportedOperationError("Object stores do not support conditional deletes.") + + +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/py.typed b/packages/zarr-storage/src/zarr_storage/py.typed new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/zarr-storage/src/zarr_storage/testing/__init__.py b/packages/zarr-storage/src/zarr_storage/testing/__init__.py new file mode 100644 index 0000000000..50e08e7c8a --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/testing/__init__.py @@ -0,0 +1,40 @@ +"""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`, `NoConditionalDeleteSuite`, +`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.testing._api import AsyncAPI, FullBackend, StoreAPI +from zarr_storage.testing._suite import ( + ConditionalDeleteSuite, + ConditionalPutSuite, + ConditionalRaceSuite, + KeyAndDirectorySuite, + KeyDirectoryConflictSuite, + NoConditionalDeleteSuite, + NoConditionalPutSuite, + PickleSuite, + StoreSuite, + UniqueGenerationsSuite, +) + +__all__ = [ + "AsyncAPI", + "ConditionalDeleteSuite", + "ConditionalPutSuite", + "ConditionalRaceSuite", + "FullBackend", + "KeyAndDirectorySuite", + "KeyDirectoryConflictSuite", + "NoConditionalDeleteSuite", + "NoConditionalPutSuite", + "PickleSuite", + "StoreAPI", + "StoreSuite", + "UniqueGenerationsSuite", +] diff --git a/packages/zarr-storage/src/zarr_storage/testing/_api.py b/packages/zarr-storage/src/zarr_storage/testing/_api.py new file mode 100644 index 0000000000..d3e7c4e305 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/testing/_api.py @@ -0,0 +1,189 @@ +"""The store surface the suite tests, and an adapter that drives it through the async methods. + +Every suite test runs twice: once against `Store`'s sync methods, once against `AsyncAPI`, which +gives the same sync-looking surface but performs every call through the matching `_async` method on +one event loop. The sync and async surfaces therefore meet one contract, checked by one set of tests. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Protocol, Self + +from zarr_storage._protocols import ( + Listable, + ListableAsync, + Readable, + ReadableAsync, + Writable, + WritableAsync, +) + +if TYPE_CHECKING: + import asyncio + from collections.abc import AsyncIterator, Iterator, Sequence + from types import TracebackType + + from typing_extensions import Buffer + + from zarr_storage._store import Store + from zarr_storage._types import ( + ByteRange, + DeleteResult, + Generation, + ListItem, + ObjectMetadata, + PutResult, + RangesResult, + ReadResult, + ) + +__all__ = ["AsyncAPI", "FullBackend", "StoreAPI", "unwrap"] + + +class FullBackend( + Readable, Writable, Listable, ReadableAsync, WritableAsync, ListableAsync, Protocol +): + """A backend with every sync and async capability.""" + + +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) -> ReadResult | None: ... + def get_ranges(self, key: str, ranges: Sequence[ByteRange]) -> RangesResult | None: ... + def get_into( + self, key: str, out: Buffer, *, byte_range: ByteRange | None = None + ) -> int | None: ... + def head(self, key: str) -> ObjectMetadata | None: ... + def exists(self, key: str) -> bool: ... + def put( + self, + key: str, + value: Buffer, + *, + if_match: Generation | None = None, + if_none_match: bool = False, + ) -> PutResult: ... + def delete(self, key: str, *, if_match: Generation | None = None) -> DeleteResult: ... + def delete_dir(self, directory: str = "") -> None: ... + def list(self, directory: str = "") -> Iterator[str]: ... + def list_dir(self, directory: str = "") -> Iterator[ListItem]: ... + def __truediv__(self, directory: str) -> Self: ... + def with_read_only(self, read_only: bool = True) -> 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`.""" + if isinstance(store, AsyncAPI): + return store.store + return store # pyright: ignore[reportReturnType] + + +async def _next(items: AsyncIterator[object]) -> object: + return await anext(items) + + +class AsyncAPI: + """`Store`'s sync-looking surface, performed through its `_async` methods on one event loop.""" + + def __init__(self, store: Store[FullBackend], runner: asyncio.Runner) -> None: + self._store = store + self._runner = runner + + @property + def store(self) -> Store[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) -> ReadResult | None: + return self._runner.run(self._store.get_async(key, byte_range=byte_range)) + + def get_ranges(self, key: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + return self._runner.run(self._store.get_ranges_async(key, ranges)) + + def get_into(self, key: str, out: Buffer, *, byte_range: ByteRange | None = None) -> int | None: + return self._runner.run(self._store.get_into_async(key, out, byte_range=byte_range)) + + def head(self, key: str) -> ObjectMetadata | None: + return self._runner.run(self._store.head_async(key)) + + def exists(self, key: str) -> bool: + return self._runner.run(self._store.exists_async(key)) + + def put( + self, + key: str, + value: Buffer, + *, + if_match: Generation | None = None, + if_none_match: bool = False, + ) -> PutResult: + return self._runner.run( + self._store.put_async(key, value, if_match=if_match, if_none_match=if_none_match) + ) + + def delete(self, key: str, *, if_match: Generation | None = None) -> DeleteResult: + return self._runner.run(self._store.delete_async(key, if_match=if_match)) + + def delete_dir(self, directory: str = "") -> None: + self._runner.run(self._store.delete_dir_async(directory)) + + def list(self, directory: str = "") -> Iterator[str]: + # `list_async` checks its argument when called; the items come one at a time. + return self._iterate(self._store.list_async(directory)) # pyright: ignore[reportReturnType] + + def list_dir(self, directory: str = "") -> Iterator[ListItem]: + return self._iterate(self._store.list_dir_async(directory)) # pyright: ignore[reportReturnType] + + def _iterate(self, items: AsyncIterator[object]) -> Iterator[object]: + 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 with_read_only(self, read_only: bool = True) -> Self: + return type(self)(self._store.with_read_only(read_only), self._runner) + + def close(self) -> None: + self._store.close() + + 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/testing/_stateful.py b/packages/zarr-storage/src/zarr_storage/testing/_stateful.py new file mode 100644 index 0000000000..3472907f3c --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/testing/_stateful.py @@ -0,0 +1,271 @@ +"""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 and conditional writes 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._errors import KeyConflictError +from zarr_storage._keys import join +from zarr_storage._types import Generation, Key, Prefix + +if TYPE_CHECKING: + from collections.abc import Callable + + from zarr_storage._types import ListItem + from zarr_storage.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 _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(key, value, if_match=Generation(object())) + except KeyConflictError: + return + raise AssertionError(f"put({join(root, key)!r}) should have raised KeyConflictError") + + def _record(self, path: str, value: bytes, generation: Generation | None) -> None: + assert generation is not 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) + assert result.applied + self._record(path, value, result.generation) + + @rule(data=st.data(), value=VALUES) + def put_if_none_match(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, if_none_match=True) + except KeyConflictError: + return + raise AssertionError( + f"put({path!r}, if_none_match) should have raised KeyConflictError" + ) + result = (self.store / root).put(key, value, if_none_match=True) + if path in self.values: + assert (result.applied, result.generation) == (False, self.generations[path]) + else: + assert result.applied + 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(key, value, if_match=expected) + if not stale and current is not None: + assert result.applied + self._record(path, value, result.generation) + else: + assert (result.applied, result.generation) == (False, current) + + @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(key, value, if_match=retired) + assert (result.applied, result.generation) == (False, self.generations.get(join(root, key))) + + @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.applied, result.generation) == (True, self.generations[path]) + self._forget(path) + else: + assert (result.applied, result.generation) == (False, None) + + @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 = (self.store / root).delete(key, if_match=expected) + if not stale and current is not None: + assert (result.applied, result.generation) == (True, current) + self._forget(path) + else: + assert (result.applied, result.generation) == (False, current) + + @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 = (self.store / root).delete(key, if_match=retired) + assert (result.applied, result.generation) == (False, self.generations.get(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) + for path, value in self.values.items(): + result = self.store.get(path) + assert result is not None + assert (bytes(result.value), result.generation) == (value, self.generations[path]) + meta = self.store.head(path) + assert meta is not None + assert (meta.size, meta.generation) == (len(value), self.generations[path]) + + def teardown(self) -> None: + if hasattr(self, "store"): + self.store.close() diff --git a/packages/zarr-storage/src/zarr_storage/testing/_suite.py b/packages/zarr-storage/src/zarr_storage/testing/_suite.py new file mode 100644 index 0000000000..5b15cc544d --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/testing/_suite.py @@ -0,0 +1,964 @@ +"""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 the sync methods and through the async methods (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 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._errors import ( + InvalidByteRangeError, + InvalidKeyError, + KeyConflictError, + ReadOnlyError, + StoreClosedError, + UnsupportedOperationError, +) +from zarr_storage._types import ( + Generation, + Key, + OffsetRequest, + Prefix, + RangeRequest, + SuffixRequest, +) +from zarr_storage.testing._api import AsyncAPI, FullBackend, StoreAPI, unwrap +from zarr_storage.testing._stateful import Capabilities, StoreMachine + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Iterator + from pathlib import Path + + from typing_extensions import Buffer + + from zarr_storage._store import Store + from zarr_storage._types import ByteRange, ListItem + +__all__ = [ + "ConditionalDeleteSuite", + "ConditionalPutSuite", + "ConditionalRaceSuite", + "KeyAndDirectorySuite", + "KeyDirectoryConflictSuite", + "NoConditionalDeleteSuite", + "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 + precondition: Literal["none", "if_none_match", "if_match_current", "if_match_stale"] + applied: bool + generation: Literal["new", "current", "none"] + + +UNCONDITIONAL_PUT_CASES = [ + PutCase(present=False, precondition="none", applied=True, generation="new"), + PutCase(present=True, precondition="none", applied=True, generation="new"), + PutCase(present=False, precondition="if_none_match", applied=True, generation="new"), + PutCase(present=True, precondition="if_none_match", applied=False, generation="current"), +] +IF_MATCH_PUT_CASES = [ + PutCase(present=True, precondition="if_match_current", applied=True, generation="new"), + PutCase(present=True, precondition="if_match_stale", applied=False, generation="current"), + PutCase(present=False, precondition="if_match_stale", applied=False, generation="none"), +] + + +@dataclass(frozen=True) +class DeleteCase: + present: bool + precondition: Literal["none", "if_match_current", "if_match_stale"] + applied: bool + generation: Literal["current", "none"] + + +UNCONDITIONAL_DELETE_CASES = [ + DeleteCase(present=False, precondition="none", applied=False, generation="none"), + DeleteCase(present=True, precondition="none", applied=True, generation="current"), +] +IF_MATCH_DELETE_CASES = [ + DeleteCase(present=True, precondition="if_match_current", applied=True, generation="current"), + DeleteCase(present=True, precondition="if_match_stale", applied=False, generation="current"), + DeleteCase(present=False, precondition="if_match_stale", applied=False, generation="none"), +] + +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_exists(store: StoreAPI) -> object: + return store.exists("a") + + +MISSING_READS: list[tuple[Callable[[StoreAPI], object], object]] = [ + (_missing_get, None), + (_missing_get_directory, None), + (_missing_get_range, None), + (_missing_get_ranges, None), + (_missing_get_into, None), + (_missing_head, None), + (_missing_exists, False), +] +MISSING_READ_IDS = ["get", "get-directory", "get-range", "get_ranges", "get_into", "head", "exists"] + + +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 + + +WRITES: list[Callable[[StoreAPI], object]] = [_put, _delete, _delete_dir] +WRITE_IDS = ["put", "delete", "delete_dir"] + + +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 _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, + _list, + _list_dir, +] +CLOSED_IDS = [ + "get", + "get_ranges", + "get_into", + "head", + "put", + "delete", + "delete_dir", + "list", + "list_dir", +] + + +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 + generation = store.put("k", bytes([fill]) * 1000).generation + assert generation is not None + written[generation] = fill + + +def _create( + store: Store[FullBackend], key: str, barrier: threading.Barrier, results: list[bool] +) -> None: + barrier.wait() + results.append(store.put(key, VALUE, if_none_match=True).applied) + + +def _check_put(store: StoreAPI, case: PutCase) -> None: + current = store.put("k", VALUE).generation if case.present else None + match case.precondition: + case "none": + result = store.put("k", b"new") + case "if_none_match": + result = store.put("k", b"new", if_none_match=True) + case "if_match_current": + assert current is not None + result = store.put("k", b"new", if_match=current) + case "if_match_stale": + result = store.put("k", b"new", if_match=_stale()) + assert result.applied is case.applied + match case.generation: + case "new": + assert result.generation is not None + assert result.generation != current + case "current": + assert result.generation == current + case "none": + assert result.generation is None + stored = store.get("k") + expected = b"new" if case.applied else (VALUE if case.present else None) + assert (None if stored is None else bytes(stored.value)) == expected + + +def _check_delete(store: StoreAPI, case: DeleteCase) -> None: + current = store.put("k", VALUE).generation if case.present else None + match case.precondition: + case "none": + result = store.delete("k") + case "if_match_current": + assert current is not None + result = store.delete("k", if_match=current) + case "if_match_stale": + result = store.delete("k", if_match=_stale()) + assert result.applied is case.applied + assert result.generation == (current if case.generation == "current" else None) + assert store.exists("k") is (case.present and not case.applied) + + +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 AsyncAPI(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 AsyncAPI(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 result is not None + 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) + assert written.applied + result = store.get("k") + assert result is not None + assert (bytes(result.value), result.generation) == (expected, written.generation) + meta = store.head("k") + assert meta is not None + 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 result is not None + assert bytes(result.value) == VALUE + + @pytest.mark.parametrize(("read", "expected"), MISSING_READS, ids=MISSING_READ_IDS) + def test_reads_of_missing_key( + self, store: StoreAPI, read: Callable[[StoreAPI], object], expected: object + ) -> None: + store.put("a/k", VALUE) + assert read(store) == expected + + # ------------------------------------------------------------------ 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 result is not None + assert bytes(result.value) == expected + out = bytearray(len(VALUE) + 1) + n = store.get_into("k", out, byte_range=byte_range) + assert n == len(expected) + assert bytes(out[:n]) == expected + if byte_range is not None: + ranges = store.get_ranges("k", [byte_range, SuffixRequest(1)]) + assert ranges is not None + 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] = {} + put = store.put("k", bytes(1000)) + assert put.generation is not None + written[put.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 AsyncAPI(store, runner) + for _ in range(200): + result = reader.get_ranges("k", [RangeRequest(0, 1), SuffixRequest(1)]) + assert result is not None + 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", UNCONDITIONAL_PUT_CASES, ids=repr) + def test_put(self, store: StoreAPI, case: PutCase) -> None: + _check_put(store, case) + + def test_put_with_both_preconditions_raises(self, store: StoreAPI) -> None: + with pytest.raises(ValueError, match="at most one"): + store.put("k", VALUE, if_match=_stale(), if_none_match=True) + + def test_concurrent_creates_apply_once(self, tmp_path: Path) -> None: + """Of many racing `if_none_match` 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", UNCONDITIONAL_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) + result = store.delete("a") + assert (result.applied, result.generation) == (False, None) + 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 + + # ------------------------------------------------------------------ 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 result is not None + assert [bytes(v) for v in result.values] == [b"9"] + meta = child.head("b/c") + assert meta is not None + 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.with_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.with_read_only() + assert (store.read_only, reader.read_only, (reader / "x").read_only) == (False, True, True) + assert reader.exists("k") + assert not store.with_read_only(False).read_only + + def test_writable_view_of_read_only_store_raises(self, store: StoreAPI) -> None: + with pytest.raises(ReadOnlyError): + store.with_read_only().with_read_only(False) + + @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.with_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.with_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"]) + def test_iterating_after_close_raises(self, store: StoreAPI, listing: str) -> None: + store.put("a", VALUE) + store.put("b", VALUE) + items = store.list() if listing == "list" else store.list_dir() + 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 is not None + assert generation not in seen + seen.add(generation) + store.delete(f"k{(i + 1) % 3}") + + +class ConditionalPutSuite: + """For backends that support `put(if_match=...)`.""" + + @pytest.mark.parametrize("case", IF_MATCH_PUT_CASES, ids=repr) + def test_put_if_match(self, store: StoreAPI, case: PutCase) -> None: + _check_put(store, case) + + +class NoConditionalPutSuite: + """For backends that refuse `put(if_match=...)`.""" + + def test_put_if_match_raises(self, store: StoreAPI) -> None: + current = store.put("k", VALUE).generation + assert current is not None + with pytest.raises(UnsupportedOperationError): + store.put("k", b"new", if_match=current) + + +class ConditionalDeleteSuite: + """For backends that support `delete(if_match=...)`.""" + + @pytest.mark.parametrize("case", IF_MATCH_DELETE_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 store.put("d/k", b"new", if_match=generation).applied: + results.append("put") + + +def _race_delete( + store: Store[FullBackend], + generation: Generation, + barrier: threading.Barrier, + results: list[str], +) -> None: + barrier.wait() + if store.delete("d/k", if_match=generation).applied: + 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 + assert generation is not None + 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 NoConditionalDeleteSuite: + """For backends that refuse `delete(if_match=...)`.""" + + def test_delete_if_match_raises(self, store: StoreAPI) -> None: + current = store.put("k", VALUE).generation + assert current is not None + with pytest.raises(UnsupportedOperationError): + store.delete("k", if_match=current) + + +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_reads_under_a_key_find_nothing(self, store: StoreAPI) -> None: + store.put("a", VALUE) + assert store.get("a/b") is None + assert store.get_into("a/b", bytearray(len(VALUE))) is None + assert store.head("a/b") is None + assert not store.exists("a/b") + assert store.get_ranges("a/b", [SuffixRequest(1)]) is None + assert not store.delete("a/b").applied + 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).with_read_only(read_only)) + 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/test_local.py b/packages/zarr-storage/tests/test_local.py new file mode 100644 index 0000000000..cbc34082a6 --- /dev/null +++ b/packages/zarr-storage/tests/test_local.py @@ -0,0 +1,388 @@ +from __future__ import annotations + +import errno +import multiprocessing +import os +import threading +import time +from typing import TYPE_CHECKING + +import pytest + +from zarr_storage import ( + Generation, + InvalidKeyError, + Key, + KeyConflictError, + Prefix, + Store, + UnsupportedOperationError, +) +from zarr_storage.backends import LocalBackend +from zarr_storage.backends._local import RESERVED_SUFFIX, _directory_lock, segment_problem +from zarr_storage.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 not store.put("k", b"y", if_none_match=True).applied + 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 store.put("k", b"y", if_none_match=True).applied + + +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(tmp_path / "sub")) + outer.delete_dir("sub") + assert inner.put("k", b"x").applied + 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"), + ("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 + + +def test_missing_root_without_create_raises(tmp_path: Path) -> None: + with pytest.raises(FileNotFoundError): + LocalBackend(tmp_path / "missing", create=False) + + +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 test_zero_concurrency_raises(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="concurrency"): + LocalBackend(tmp_path, concurrency=0) + + +def _create( + store: Store[LocalBackend], key: str, barrier: threading.Barrier, results: list[bool] +) -> None: + barrier.wait() + results.append(store.put(key, b"x", if_none_match=True).applied) + + +@pytest.mark.parametrize("overlapping_roots", [False, True]) +def test_concurrent_creates_through_overlapping_roots( + tmp_path: Path, overlapping_roots: bool +) -> None: + """Of many racing `if_none_match` writes to one key, exactly one applies, even through + backends whose roots overlap.""" + outer = Store(LocalBackend(tmp_path)) + inner = Store(LocalBackend(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 Store(LocalBackend(root)).put(key, b"x", if_none_match=True).applied + + +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)) + assert store.put("a/k", b"x").applied + result = store.get("a/k") + assert result is not None + 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 store.put("P/D/k", b"y", if_none_match=True).applied + + +def test_delete_dir_leaves_a_symlinked_directory_alone(tmp_path: Path) -> None: + outside = tmp_path / "outside" + outside.mkdir() + (outside / "keep").write_bytes(b"x") + store = Store(LocalBackend(tmp_path / "root")) + (tmp_path / "root" / "link").symlink_to(outside) + store.delete_dir("link") + assert (outside / "keep").exists() + + +def test_delete_dir_removes_a_nested_backends_staging(tmp_path: Path) -> None: + outer = Store(LocalBackend(tmp_path)) + inner = Store(LocalBackend(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: + outcomes[key] = store.put(key, b"x").applied + 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("k", b"x", if_none_match=True), + lambda s: s.put("k", b"x", if_match=Generation(object())), + lambda s: s.delete("k", if_match=Generation(object())), + ], + ids=["put-if_none_match", "put-if_match", "delete-if_match"], +) +def test_conditional_writes_on_a_filesystem_that_rounds_times_raise( + tmp_path: Path, write: Callable[[Store[LocalBackend]], object], monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(LocalBackend, "_probe_exact_times", _coarse) + store = Store(LocalBackend(tmp_path)) + with pytest.raises(UnsupportedOperationError, match="rounds file times"): + write(store) + assert store.put("k", b"x").applied diff --git a/packages/zarr-storage/tests/test_memory.py b/packages/zarr-storage/tests/test_memory.py new file mode 100644 index 0000000000..694018ad4a --- /dev/null +++ b/packages/zarr-storage/tests/test_memory.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import pickle +from typing import TYPE_CHECKING + +from zarr_storage import Store +from zarr_storage.backends import MemoryBackend +from zarr_storage.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/test_obstore.py b/packages/zarr-storage/tests/test_obstore.py new file mode 100644 index 0000000000..082df001ab --- /dev/null +++ b/packages/zarr-storage/tests/test_obstore.py @@ -0,0 +1,176 @@ +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING + +import obstore +import pytest +from obstore.exceptions import GenericError +from obstore.store import LocalStore, MemoryStore + +from zarr_storage import ObjectMetadata, RangeRequest, Store +from zarr_storage.backends import ObjectStoreBackend +from zarr_storage.backends._obstore import _empty_read_or_raise, _generation +from zarr_storage.testing import ( + ConditionalPutSuite, + KeyAndDirectorySuite, + KeyDirectoryConflictSuite, + NoConditionalDeleteSuite, + NoConditionalPutSuite, + PickleSuite, + StoreSuite, + UniqueGenerationsSuite, +) + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Callable + from pathlib import Path + + +_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, + NoConditionalDeleteSuite, + KeyAndDirectorySuite, + NoBlockingCallsInAsyncRuns, +): + def make_store(self, directory: Path) -> Store[ObjectStoreBackend]: + return Store(ObjectStoreBackend(MemoryStore())) + + +class TestObjectStoreLocal( + StoreSuite, + NoConditionalPutSuite, + NoConditionalDeleteSuite, + 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 result is not None + 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.list_async("a"))) + + +def _list_dir_a_async(store: Store[ObjectStoreBackend]) -> object: + return asyncio.run(_collect(store.list_dir_async("a"))) + + +def _get_ab_async(store: Store[ObjectStoreBackend]) -> object: + return asyncio.run(store.get_async("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) diff --git a/packages/zarr-storage/tests/test_store.py b/packages/zarr-storage/tests/test_store.py new file mode 100644 index 0000000000..9ca73c3607 --- /dev/null +++ b/packages/zarr-storage/tests/test_store.py @@ -0,0 +1,117 @@ +"""`Store` behavior that doesn't depend on a backend's own implementation.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest + +from zarr_storage import ( + Generation, + ObjectMetadata, + OffsetRequest, + RangeRequest, + RangesResult, + ReadResult, + Store, + SuffixRequest, +) +from zarr_storage._byte_range import resolve +from zarr_storage.backends import MemoryBackend + +if TYPE_CHECKING: + from collections.abc import Sequence + + from zarr_storage import ByteRange + + +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 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) -> ReadResult | None: + data = self._values.get(path) + if data is None: + return None + start, end = resolve(byte_range, len(data)) + return ReadResult(memoryview(data)[start:end], Generation(0)) + + def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + raise NotImplementedError + + def head(self, path: str) -> ObjectMetadata | None: + data = self._values.get(path) + return None if data is None else ObjectMetadata(len(data), Generation(0), None) + + +@pytest.mark.parametrize( + ("byte_range", "expected"), + [(None, b"0123"), (RangeRequest(1, 3), b"12"), (SuffixRequest(1), b"3")], +) +def test_get_into_without_backend_support(byte_range: ByteRange | None, expected: bytes) -> None: + """A backend without `get_into` is read with `get` and copied into the buffer.""" + store = Store(_ReadOnlyBackend({"a/k": b"0123"})) / "a" + out = bytearray(4) + n = store.get_into("k", out, byte_range=byte_range) + assert (n, bytes(out[: n or 0])) == (len(expected), expected) + assert store.get_into("missing", out) is None + + +def test_get_into_without_backend_support_short_buffer_raises() -> None: + store = Store(_ReadOnlyBackend({"k": b"0123"})) + with pytest.raises(ValueError, match="holds"): + store.get_into("k", bytearray(3)) + + +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) diff --git a/packages/zarr-storage/towncrier-template.md b/packages/zarr-storage/towncrier-template.md new file mode 100644 index 0000000000..d3616fe8c5 --- /dev/null +++ b/packages/zarr-storage/towncrier-template.md @@ -0,0 +1,130 @@ +{#- +This package's copy of towncrier's default Markdown template. The one +change: each entry's continuation lines are indented by four spaces, not +two, and entries are separated by a blank line, so an entry with a +second paragraph or a nested list stays one list item in Python-Markdown, +which renders the docs' release notes page, as well as in CommonMark. +Without both, Python-Markdown ends the list at the second paragraph and +runs the later entries together as one paragraph. +-#} +{#- +══════════════════════════════════════════════════════════════════════════════ +TOWNCRIER MARKDOWN TEMPLATE +══════════════════════════════════════════════════════════════════════════════ + +─── Macro: heading ───────────────────────────────────────────────────────── +Purpose: + Generates Markdown headings with the appropriate number of # characters. + Based on header_prefix (default: "#") and the level argument. + +Arguments: + level The relative heading level (1=#, 2=##, 3=###, etc.) +-#} +{%- macro heading(level) -%} + {{- "#" * ( header_prefix | length + level -1 ) }} +{%- endmacro -%} + +{#- +─── Variable: newline ────────────────────────────────────────────────────── +Purpose: + Consistent newline handling. -#} +{%- set newline = "\n" -%} + +{#- ════════════════════════ TEMPLATE GENERATION ════════════════════════ -#} +{#- ─── TITLE HEADING ─── #} +{#- render_title is false when title_format is specified in the config #} +{%- if render_title %} + {%- if versiondata.name %} + {{- heading(1) ~ " " ~ versiondata.name ~ " " ~ versiondata.version ~ " (" ~ versiondata.date ~ ")" ~ newline }} + {%- else %} + {{- heading(1) ~ " " ~ versiondata.version ~ " (" ~ versiondata.date ~ ")" ~ newline }} + {%- endif %} +{%- endif %} +{#- If title_format is specified, we start with a new line #} +{{- newline }} + +{%- for section, _ in sections.items() %} + {#- ─── SECTION HEADING ─── #} + {%- if section %} + {{- newline }} + {{- heading(2) ~ " " ~ section ~ newline }} + {{- newline }} + {%- endif %} + + {%- if sections[section] %} + + {%- for category, val in definitions.items() if category in sections[section] %} + {%- set issue_pks = [] %} + {#- ─── CATEGORY HEADING ─── #} + {#- Increase heading level if section is not present #} + {{- heading(3 if section else 2) ~" " ~ definitions[category]['name'] ~ newline }} + {{- newline }} + + {#- ─── RENDER ENTRIES ─── #} + {%- for text, values in sections[section][category].items() %} + {#- A blank line between entries: Python-Markdown starts a new list + item after an entry of several paragraphs only after one. #} + {%- if not loop.first %} + {{- newline }} + {%- endif %} + {#- Prepare the string of issue numbers (e.g., "#1, #9, #142") #} + {%- set issue_pks = [] %} + {%- for v_issue in values %} + {%- set _= issue_pks.append(v_issue.split(": ", 1)[0]) %} + {%- endfor %} + {%- set issues_list = issue_pks | join(", ") %} + + {#- Check if text contains a sublist #} + {%- set text_has_sublist = (("\n - " in text) or ("\n * " in text)) %} + + {#- CASE 1: No text, only issues #} + {#- Output: - #1, #9, #142 #} + {%- if not text and issues_list %} + {{- "- " ~ issues_list ~ newline }} + + {#- Cases where both text and issues exist #} + {%- elif text and issues_list %} + {%- if text_has_sublist %} + {#- CASE 3: Text with sublist #} + {#- Output: - TEXT\n\n (#1, #9, #142) #} + {{- "- " ~ (text | indent(2)) ~ newline ~ newline ~ " (" ~ issues_list ~ ")" ~ newline }} + {%- else %} + {#- CASE 2: Text, no sublist #} + {#- Output: - TEXT (#1, #9, #142) #} + {{- "- " ~ (text | indent(2)) ~ " (" ~ issues_list ~ ")" ~ newline }} + {%- endif %} + + {%- elif text %} + {#- Implicit Case: Text, but no issues #} + {#- Output: - TEXT #} + {{- "- " ~ (text | indent(2)) ~ newline }} + {%- endif %} + {%- endfor %} + + {#- New line between list and link references #} + {{- newline }} + + {#- Link references #} + {%- if issues_by_category[section][category] and "]: " in issues_by_category[section][category][0] %} + {%- for issue in issues_by_category[section][category] %} + {{- issue ~ newline }} + {%- endfor %} + {{- newline }} + {%- endif %} + + {#- No changes in this category #} + {%- if sections[section][category]|length == 0 %} + {{- newline }} + {{- "No significant changes." ~ newline * 2 }} + {%- endif %} + {%- endfor %} + {%- else %} + {#- No changes in this section #} + {{- "No significant changes." ~ newline * 2 }} + {%- endif %} +{%- endfor %} +{#- +Newline at the end of the rendered newsfile content. +In this way the there are 2 newlines between the latest release and the previous release content. +-#} +{{- newline -}} diff --git a/packages/zarr-storage/uv.lock b/packages/zarr-storage/uv.lock new file mode 100644 index 0000000000..4c68fc2367 --- /dev/null +++ b/packages/zarr-storage/uv.lock @@ -0,0 +1,275 @@ +version = 1 +revision = 5 +requires-python = ">=3.11" + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "hypothesis" +version = "6.170.15" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sortedcontainers" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/96/ec/59f14eb701087710888b66bfef2dc8bee9dd4a364c69a732db0cc1d3d2dc/hypothesis-6.170.15.tar.gz", hash = "sha256:a4a57e5fb106ecb29cad37e22e411d957e20d933bfb9fb029e1999b1deb8a0b6", size = 521997, upload-time = "2026-11-06T09:54:57.339Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/84/cf/3b56a81685915f6bf0d67b3a6c1139fd9bd4583066161823834e42b9eaa7/hypothesis-6.170.15-cp311-abi3-macosx_10_12_x86_64.whl", hash = "sha256:db8211e0a56fa29bf9e5d9ff9cd969a91ff4e5ffa8fb4983d3dd788253aeee2c", size = 800537, upload-time = "2026-11-06T09:53:36.823Z" }, + { url = "https://files.pythonhosted.org/packages/b6/09/477b3233cca8c447a6dc5fcc076a7294a4fdacb615d960695f6970d706dc/hypothesis-6.170.15-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:34e0859a53f20200f39db3f9cd92112eb6034c31dc670e88d56d8725f453562d", size = 795693, upload-time = "2026-11-06T09:54:14.601Z" }, + { url = "https://files.pythonhosted.org/packages/7c/7a/34e042f1545472abe29ecf9eebac6f748096580f6fb831817f097addbe29/hypothesis-6.170.15-cp311-abi3-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:5c5980821384206939c1c9d519b7adfb80b54d07e669ab0d36fe877f08cff07a", size = 1162432, upload-time = "2026-11-06T09:53:55.461Z" }, + { url = "https://files.pythonhosted.org/packages/3a/7f/95b7b04d2b7e45669db446ee10d97f5d04b143bba380559a7f3a7e0c5b1f/hypothesis-6.170.15-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f29339b5cd4c2a221885e8b7ddbd447b4dc7ee14f763a6f5aaff726d4d3fd5ed", size = 1124598, upload-time = "2026-11-06T09:54:26.015Z" }, + { url = "https://files.pythonhosted.org/packages/33/8e/896172d9706bfe2e09c9154fecb11c7b76e50014442783dd9d5b404c8c84/hypothesis-6.170.15-cp311-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:d836a61c3dd94c6fc4677f4d0d95d30b92eb0ceab6f2b5c58e35c32545583170", size = 1155097, upload-time = "2026-11-06T09:54:47.123Z" }, + { url = "https://files.pythonhosted.org/packages/29/33/b8791c6a9b4232c3cc8f592d3e36175bcb4bad6203f7e461db0a4f5fa11b/hypothesis-6.170.15-cp311-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:d18ffd069360589a66ed125db62f12b490b3b9f6d47e5fd2505f1089d63a0f17", size = 1148988, upload-time = "2026-11-06T09:54:33.101Z" }, + { url = "https://files.pythonhosted.org/packages/87/2c/3ee87dd6fdec16ce55a4aeb5f72ae24756855cdc4ee87637fb68c4daeadc/hypothesis-6.170.15-cp311-abi3-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:7636424c7b1477fdd279fce5a210b67687a3024ac7759fe2e46a767a76f8761c", size = 1201778, upload-time = "2026-11-06T09:53:49.736Z" }, + { url = "https://files.pythonhosted.org/packages/6b/6a/f2757fde7d1b3b5dda6df3441d346b59c60627f2c216d966739289149903/hypothesis-6.170.15-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:99a1a4711b5276e5bfc3aa0cca034d0e45f8696a46ac8dce008308f580c18234", size = 1168007, upload-time = "2026-11-06T09:54:34.331Z" }, + { url = "https://files.pythonhosted.org/packages/8d/79/b6ff2a2840e4bcdea5c4cf1bcdd3803954a632beec16cb9d77a9ee8ddbb8/hypothesis-6.170.15-cp311-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:f545a04342a53008fa696a0592f0a026278ee61fab04f3e9e395d0c7eba42fef", size = 1124154, upload-time = "2026-11-06T09:53:24.354Z" }, + { url = "https://files.pythonhosted.org/packages/52/d0/19bc4a98e9583936dbe6e754014ad1133d3a43c9068a880c4e91ce384fad/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1f11d685322a56ee73c2a7566ec9d1195740313c3b965bad3121c340ec0e657b", size = 1299503, upload-time = "2026-11-06T09:53:12.86Z" }, + { url = "https://files.pythonhosted.org/packages/ee/06/fad2d1546c08eb4133f9478716bf6bc5f881e0d06b5b4f1faf34fd515a5a/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:f6d5d34fa6b56f236ad9659043123efb85391a8a5640f067c9de82b0be0bff73", size = 1428191, upload-time = "2026-11-06T09:54:44.43Z" }, + { url = "https://files.pythonhosted.org/packages/ca/cd/71d43284cca9c5145ceae04ddac1adfc57e9da57cf8efd30c0876844c9bf/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_i686.whl", hash = "sha256:2ff9983a58647b03754fa3d1005e59a9c563e15256340fc062b4a34c7969d52a", size = 1382322, upload-time = "2026-11-06T09:54:06.405Z" }, + { url = "https://files.pythonhosted.org/packages/0f/56/5754189cd709d4eb34601f8ebb57f1d2381b2dd74f62352ba6b84bce4a12/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:6e461d7b392a630593134611ebb1fce6baba88dbbf4f07661a37ff58ff4e1b6a", size = 1278225, upload-time = "2026-11-06T09:52:59.772Z" }, + { url = "https://files.pythonhosted.org/packages/7e/a9/5224ea74356981f01222c42f0acc55821fb5aadf3f1f15adc797c7eefbd2/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:62c0675a837bbe0f3f7c7a89b701bee159759840c23b9bec9d565d3434fb0b3a", size = 1294018, upload-time = "2026-11-06T09:54:29.127Z" }, + { url = "https://files.pythonhosted.org/packages/9d/c5/297f16660b15eacb2872af9fb127e7fe83f48f6f9caf223cb5abd5a25bd8/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:124b0b9962ff6b25786692b7b6cb0065f8bb7870081ddd9baf4745b0ff4a5c7a", size = 1333737, upload-time = "2026-11-06T09:54:03.427Z" }, + { url = "https://files.pythonhosted.org/packages/19/18/7e35ba1bc1f0e3ec55d9d97864db42b5ffeea92766ae4bd7ced0f77cc930/hypothesis-6.170.15-cp311-abi3-win32.whl", hash = "sha256:d34e54f485777eb217c85c425ddbe7b278ef56540feedb5de4097a5abc9f5719", size = 687717, upload-time = "2026-11-06T09:54:40.259Z" }, + { url = "https://files.pythonhosted.org/packages/fa/d6/c16f5abdb56baa2d401de38c2f758090796c1716fed9aa690179772e6adf/hypothesis-6.170.15-cp311-abi3-win_amd64.whl", hash = "sha256:de9fe573a4955b0cf0354822fbfe9b79882e8de02f26287313fe1ad47ba3e69f", size = 693782, upload-time = "2026-11-06T09:53:17.157Z" }, + { url = "https://files.pythonhosted.org/packages/13/7a/ae3b7fdd44c30b662f27344ccb810d080d11b7f557c2cffa88d01e677295/hypothesis-6.170.15-cp311-abi3-win_arm64.whl", hash = "sha256:de5e11c568fd411a3cf07e4e34d4f8cf07d638de2f254c8bd87c1879679cdd9a", size = 692109, upload-time = "2026-11-06T09:53:52.599Z" }, + { url = "https://files.pythonhosted.org/packages/22/fa/4f61c0e5487d75d9ef20bb6d7b9e13b5aabf89d249896d9af0a648578be7/hypothesis-6.170.15-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:679635cd52626790214f879a8bdbb877923333fbd18905c591af41bd74d2f8db", size = 801251, upload-time = "2026-11-06T09:53:45.982Z" }, + { url = "https://files.pythonhosted.org/packages/51/c2/8eb51b3b243248fc7289b37aa78caeff847b98e7a35ba6f6e12a846d68ec/hypothesis-6.170.15-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f95b532f23bed43ef3c45fbd19baf4717687a4993fa6f42fc704fbde18bd744c", size = 796937, upload-time = "2026-11-06T09:54:31.637Z" }, + { url = "https://files.pythonhosted.org/packages/af/fe/80d94b0366d3408078c32758f7149592fdf963d431e52188728e5380d806/hypothesis-6.170.15-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9f5937e70c636ee46bd2242d9ef120d19744e63ce7d17a92fd4c9f57ef62b1c3", size = 1125542, upload-time = "2026-11-06T09:54:16.018Z" }, + { url = "https://files.pythonhosted.org/packages/fd/b4/c9dfacdfa074ebcee35ad8d9e6436480a45b543bd42ab92fa556e3bee113/hypothesis-6.170.15-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ecbd6294a636594580689debc3011a0ca3eb76577770f661224314202f107e14", size = 1168312, upload-time = "2026-11-06T09:53:22.993Z" }, + { url = "https://files.pythonhosted.org/packages/66/dd/29996ba7a8ef7eaea1493dffda4bfb04e85180a2f45d3d9ab7793ada3722/hypothesis-6.170.15-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:efaee8533a06b6a2382ff7c336ea5a747c1b22a4e97c19bfe825a02388f56d2d", size = 1300279, upload-time = "2026-11-06T09:54:30.502Z" }, + { url = "https://files.pythonhosted.org/packages/57/2d/b4be9bbb76ac5079af9cd5cf484e3e0ad91f60a7e98c69d56ac623d55573/hypothesis-6.170.15-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4af2d31c00306707166b4f39e5208d2585f9ef4accb10586534101eb32f243fb", size = 1334296, upload-time = "2026-11-06T09:53:08.948Z" }, + { url = "https://files.pythonhosted.org/packages/69/55/f0677edf64249c5d91ae9387678bfd43ae0f54905fd2a4dbede9cbaf1e0e/hypothesis-6.170.15-cp311-cp311-win_amd64.whl", hash = "sha256:b48cb85180255ec3eb3b3e5d49068c9ad447b25e34fccafdabae63d2c3d854ad", size = 693893, upload-time = "2026-11-06T09:54:49.687Z" }, + { url = "https://files.pythonhosted.org/packages/91/db/84d418c965fe889d21e7791f946f7c893bf492bcedb38f3f5b8eb405a035/hypothesis-6.170.15-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:29223a2d180e463f1205b7e5eb397db0c4827de06f2ae571b00c392d355c410e", size = 802327, upload-time = "2026-11-06T09:54:20.994Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8f/63d8644162728ba8b2c8a8a8b6a34476663c964cc0f6885c19f84ead40d6/hypothesis-6.170.15-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7953ad8f123b4289801b833666aaab757ba52e91ed687d954eb26f4af7328e5b", size = 794302, upload-time = "2026-11-06T09:54:24.828Z" }, + { url = "https://files.pythonhosted.org/packages/ec/2e/d479c69c08d5aabd7e6499f3dddc22b241db42922d746d05df9548213229/hypothesis-6.170.15-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b1f37920547eafa77814bc9b638e47299562123023bdf3c9cb002795bb90fc92", size = 1123978, upload-time = "2026-11-06T09:54:36.215Z" }, + { url = "https://files.pythonhosted.org/packages/ee/e2/824c524d04152e5c26111247d2d4dbf210d43df7c6612f7ff22c20de5abc/hypothesis-6.170.15-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e9e20ec17d2095e9314ea232b4e34b5510def0d9e7a7e764cc70cae88fe4b0c4", size = 1167677, upload-time = "2026-11-06T09:54:55.123Z" }, + { url = "https://files.pythonhosted.org/packages/ce/49/4aab201f1fd0109560d985076a4c852c1abda14984470369bf29ea89ade3/hypothesis-6.170.15-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:11c541cf103c784306f6037e5ab962cbe3d5891d36fd98df993f38d7ddbcd360", size = 1298862, upload-time = "2026-11-06T09:53:51.237Z" }, + { url = "https://files.pythonhosted.org/packages/db/a7/83fc4ef9484deefd955949a9a72a14d9435b6ace339feb27de25bf286e29/hypothesis-6.170.15-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:eecdcd38395facf6ea3af90320a574f5e63c310c194d2a0eb75f121223942386", size = 1333300, upload-time = "2026-11-06T09:53:39.58Z" }, + { url = "https://files.pythonhosted.org/packages/d5/18/5f1a5ce07a9e6b7a2cbfb6a8bceb9b5161de5477abb8d99d659a898b7554/hypothesis-6.170.15-cp312-cp312-win_amd64.whl", hash = "sha256:7dfb3d92df4faa67d3c975d1ecdefabc5a2481b789048f52cd5fb775c6c517b8", size = 691422, upload-time = "2026-11-06T09:54:05.043Z" }, + { url = "https://files.pythonhosted.org/packages/16/16/d75485989f250dd5017d1627902961c2f985686355f50d10170a2490d970/hypothesis-6.170.15-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:e3f478d4d9e13d528e352a4d938dea10b25793663ac752d774d7d35b008a1b45", size = 802290, upload-time = "2026-11-06T09:53:33.892Z" }, + { url = "https://files.pythonhosted.org/packages/24/45/54e42ac718e1164090c04b588024e4818a8e2a28b9002faa21e9fd59ab67/hypothesis-6.170.15-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9c92af3f0c8844d9eba793a4371035a45e88bb59579a1408ce5d3cceb9e2b1da", size = 794293, upload-time = "2026-11-06T09:54:09.14Z" }, + { url = "https://files.pythonhosted.org/packages/b8/ee/1a81a7d544e321165159a07e666f6c302ec109beccca3b37f8d0de54e0cd/hypothesis-6.170.15-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:dce4d989f6b9c0a589b944591f13de3dff34e186c14401e11b819fed81d70a5b", size = 1123881, upload-time = "2026-11-06T09:53:01.454Z" }, + { url = "https://files.pythonhosted.org/packages/c9/07/4d506b2e37601ec8b38a0c4b8f547dd344bd8eccd577dbd0543a744fce03/hypothesis-6.170.15-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f25261d1656f830a78863844be5fb55cd0208154dc9ddec85d44fe691488c557", size = 1167605, upload-time = "2026-11-06T09:53:32.309Z" }, + { url = "https://files.pythonhosted.org/packages/a5/77/a88824d02272f149870e36aaad0197dc5a186f53a1896ea3117f250b8414/hypothesis-6.170.15-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5ae92fa40b57c1cd331d63fe6f95aecfdb6aa32f15b4c418c108c41fcd4aef84", size = 1298841, upload-time = "2026-11-06T09:53:15.809Z" }, + { url = "https://files.pythonhosted.org/packages/68/b9/6e1b55b6b32926cebb7ef37076d8fda9d0f87045e90e4b75e93eeb9a56ac/hypothesis-6.170.15-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b829dc3cbd73fe08c02151afc438448180907da62c154cfa68abd178eafd4d48", size = 1333319, upload-time = "2026-11-06T09:52:57.279Z" }, + { url = "https://files.pythonhosted.org/packages/c8/77/7d2009c663eb26b329c622091f7593ee6c90eac663f389fdf7311d44b035/hypothesis-6.170.15-cp313-cp313-win_amd64.whl", hash = "sha256:1f7ede44b875dddd8f3e7562e6702c363e82c6fb680b0fe079536bae662987f8", size = 691393, upload-time = "2026-11-06T09:54:56.287Z" }, + { url = "https://files.pythonhosted.org/packages/96/85/977d43b789fe4ca530e76020bbd2db07a9af3c17a4bf27a276416b6540e5/hypothesis-6.170.15-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:ffac67d06f765fd000a132e71117ee92dbd59863cea18403220ca4e39b50397f", size = 802549, upload-time = "2026-11-06T09:54:17.455Z" }, + { url = "https://files.pythonhosted.org/packages/cb/1a/51e637155a8c897774463389f1341ec8d466a9860cf5e004689866c557b2/hypothesis-6.170.15-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:82b613ee882068e781d810eb73a8195b59edd6cc47e8acbe4971562044a99c83", size = 794333, upload-time = "2026-11-06T09:54:27.915Z" }, + { url = "https://files.pythonhosted.org/packages/24/c1/ea255465b482ba5fc5f678e4347d6c6bbe878c827ca652d634328be96534/hypothesis-6.170.15-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:eb6fe3d1cb91d4f14fd307f10ae969ef7e866c16e4010a750d1cade145dfd764", size = 1124402, upload-time = "2026-11-06T09:53:02.773Z" }, + { url = "https://files.pythonhosted.org/packages/7a/69/32a05f0ae41f699f30ff872be74fe46ee1d45ead7abfb114afe3a4b4a3ee/hypothesis-6.170.15-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f91f27a89e8d55c7f043cb1e10705096236d4f7bcb35f3ac4f821e0c9b9bcd05", size = 1167795, upload-time = "2026-11-06T09:54:00.357Z" }, + { url = "https://files.pythonhosted.org/packages/c2/fb/c16886cea3a7ae3045093480775eb058eed549f41aa0e21a8d96aa7d51b1/hypothesis-6.170.15-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e0e4ab687c0f2bd62b7963dc8c3c8d29211cdc6db7ce05d37ef2a20d21219c18", size = 1299361, upload-time = "2026-11-06T09:53:04.441Z" }, + { url = "https://files.pythonhosted.org/packages/b7/f3/ad57518f76503276c896388affeccca1ffb1cccc529d063dac588c4bb652/hypothesis-6.170.15-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:b01d130c103fdf78a4a748cae7d095edfe5d37534828413a509936fb3567db61", size = 1333515, upload-time = "2026-11-06T09:53:18.642Z" }, + { url = "https://files.pythonhosted.org/packages/2b/08/500fbe05990d886d4502fa334f6cf03607be473b2a2efffb660238135f05/hypothesis-6.170.15-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:1138c03edf4c4401afb28e50255644b4ab4e1ad52864456cd4e84458ba8c671a", size = 634104, upload-time = "2026-11-06T09:54:22.317Z" }, + { url = "https://files.pythonhosted.org/packages/41/53/11e3260a72024f41246061ad204627f8336bfbf0ec2b180648d01a05491f/hypothesis-6.170.15-cp314-cp314-win_amd64.whl", hash = "sha256:57ae2617424f5bb55af0146b47e0aff64a9d6677a4d5216cf2a66bd3bda0d457", size = 691115, upload-time = "2026-11-06T09:53:41.223Z" }, + { url = "https://files.pythonhosted.org/packages/ba/41/655fca0f45b7ea6df6b5bb70ab52b740cc6bc30b971366036eddd36a77c9/hypothesis-6.170.15-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:c0514f3f8ab5d56103b756317dedc8476945b0633e51112312247e3caecd0eb2", size = 800640, upload-time = "2026-11-06T09:53:05.61Z" }, + { url = "https://files.pythonhosted.org/packages/a5/89/6bf52da8b15846c7263eac9fcffb89cc1d1c82f96ca5b839a0d00bb3aa3a/hypothesis-6.170.15-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:cc5434cde3b22c900dfe01f891804b48f6e2aa93e891ca98a14c07dd04fa6d54", size = 792915, upload-time = "2026-11-06T09:53:11.508Z" }, + { url = "https://files.pythonhosted.org/packages/11/f9/a0c2a356c7a3a4b65ec2f80382c9ea5acc1a86247ac64ecb1b7dfc38ee95/hypothesis-6.170.15-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f22900eec7df2696073c05f60c666654eaa93f17aebe8964f751d75b131dcd90", size = 1122841, upload-time = "2026-11-06T09:53:21.626Z" }, + { url = "https://files.pythonhosted.org/packages/ef/f1/d4fa867fae5a733e4041720622417804bcfb79c00d265c5451243a5aba20/hypothesis-6.170.15-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7288412dfba6b5a6f875279a25409eda6b25d097c26ea710540f904287c55d06", size = 1166715, upload-time = "2026-11-06T09:54:42.908Z" }, + { url = "https://files.pythonhosted.org/packages/04/5d/cbf8acf14caa5a2e4d34dd088a507cc84da49a660b6f532104d8afdb2903/hypothesis-6.170.15-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7d546a5d6a5549a6b34304f7315d20aff7afd206996592329877da529b9d9153", size = 1297608, upload-time = "2026-11-06T09:53:29.22Z" }, + { url = "https://files.pythonhosted.org/packages/9c/a0/912a0ebf3ab19b39235233f9e1664147f6e842aa6915828d68c1d1e13f27/hypothesis-6.170.15-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:bd8b36d0403eff6473686c0e4d8b7704780ebf548b0b2cc86cb9cbbbe64f8c2f", size = 1332521, upload-time = "2026-11-06T09:53:47.664Z" }, + { url = "https://files.pythonhosted.org/packages/37/36/d9286c792272651db4059a3497a19cc7f4f60e0452c862274d506b0132fd/hypothesis-6.170.15-cp314-cp314t-win_amd64.whl", hash = "sha256:67eb006925a3a49ddc4a48d9af8314349291a7eee9b2baea6beb93bc48211ead", size = 691229, upload-time = "2026-11-06T09:54:45.888Z" }, + { url = "https://files.pythonhosted.org/packages/91/42/b152b66db2061b47ff928efc7162c2dcf4591d92dab19b3c574af3552220/hypothesis-6.170.15-cp315-abi3.abi3t-macosx_10_12_x86_64.whl", hash = "sha256:e007ff1dfb8bfa228b97ed6695325cfa1ba6487c7e1175c884e8795e71fb41a5", size = 800291, upload-time = "2026-11-06T09:54:07.899Z" }, + { url = "https://files.pythonhosted.org/packages/67/6f/49fe04f0b4cfd142d474e08a1855ea093c7367e6ff33e7c5d4a64592f743/hypothesis-6.170.15-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:742846b0e2e31640acf8bba7c2b8b6eb9cecd6817a906af6d4b5ced9db697660", size = 792763, upload-time = "2026-11-06T09:54:51.025Z" }, + { url = "https://files.pythonhosted.org/packages/88/e6/61ec7fb3b84dd8d8644d6a322d5dba4501e2f32d0b10b8b5467e7d6defd4/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:508488dd4e92e03ecd16ea086f33d766855ed1febd322a439ec231c920b1740a", size = 1158761, upload-time = "2026-11-06T09:54:02.105Z" }, + { url = "https://files.pythonhosted.org/packages/8d/ae/c9eb63eb1b2d935551494aa42ecf91bb214d89c52631854dfbb09ccb6d39/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ccc6a9ce18dced7f0d2cba36f334f44697c1c6e692949c1bbd0bc67a7065c86a", size = 1121659, upload-time = "2026-11-06T09:54:12.041Z" }, + { url = "https://files.pythonhosted.org/packages/0a/44/b99e644480a31153de52489dc4c062df5f82a10fbb2b699d0f17ecb08171/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:b8a0b5b3e21a1d2e235f42a813fbf04872196ad53151fdd4cfe02723db699f8d", size = 1152560, upload-time = "2026-11-06T09:54:41.478Z" }, + { url = "https://files.pythonhosted.org/packages/f8/0a/bfc1c697f34e395d635f49d2a29f1bfc41a0eccdcf9fba32fb33601325de/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:b59187094929ce6d5351a6f92e7f3831cd463fe69591def6ebd0023a3073af2e", size = 1146287, upload-time = "2026-11-06T09:53:42.894Z" }, + { url = "https://files.pythonhosted.org/packages/bb/69/90fac02af55ccbea1d1b3bbc72512c4f998e3fabc6b375c8c0afd0e6003f/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:0ecf4e2948c3de57ea12d66f6cf6c0e3ad88b5eae0d216cfa2922800ba5522a7", size = 1200042, upload-time = "2026-11-06T09:54:37.409Z" }, + { url = "https://files.pythonhosted.org/packages/f8/eb/6810206ee4864b39da6e81b2318516773d5a89b0e2132c00dfc9aa760179/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:55e3dcd5d8fbfd5a97018ff2712f375148b62ef537490c281a198977f3588578", size = 1165971, upload-time = "2026-11-06T09:53:25.72Z" }, + { url = "https://files.pythonhosted.org/packages/e1/c8/ebfb57d277e571c207d690efa56462f1f582721e5170bb86af42c3f97b07/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux_2_31_riscv64.whl", hash = "sha256:417fe54775f846fa4903bb2094ce3092a0ecc107db6676b21fd8069fcc328cb9", size = 1120269, upload-time = "2026-11-06T09:53:56.767Z" }, + { url = "https://files.pythonhosted.org/packages/8a/2b/69dff10b56fbc21dc0d240de503d741ec14cb6819f67530bca0b6ff7c5af/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:47438186039fcfba3a245bb407490d442ce2c9cce4370565f1bfcdcb887e91e2", size = 1296436, upload-time = "2026-11-06T09:53:54.24Z" }, + { url = "https://files.pythonhosted.org/packages/5f/43/42b037bb17dca205f5953b11792ecc2c73dbf7ec743d5dc490d010edb9b0/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_armv7l.whl", hash = "sha256:372b05075d4a259c5ebf3fcf43dc689ef5d4335bed9d0c9dd25d14997842c0c0", size = 1425535, upload-time = "2026-11-06T09:53:27.106Z" }, + { url = "https://files.pythonhosted.org/packages/a8/29/bb3050f958b0e3156909011afdcc07812b58a47eba50f53a39d931c1256b/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_i686.whl", hash = "sha256:2161fb65416bf8da3b1c3119aa92ea63cc177fd88249bf7dc4ca64b4872e0bd1", size = 1379162, upload-time = "2026-11-06T09:54:23.523Z" }, + { url = "https://files.pythonhosted.org/packages/a5/db/30a2291c92cd437b0c8184bcead204add93d174a1317894dc50ddd3a681d/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_ppc64le.whl", hash = "sha256:b3db4c8aecd13e043c419d90ccb683fdf19711b547ca9d23e685a35157d4657f", size = 1274757, upload-time = "2026-11-06T09:54:38.796Z" }, + { url = "https://files.pythonhosted.org/packages/a5/0a/5e1bf0060a1f9486f6cad2b512b5101526dc376565eb669c20964ccee730/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_riscv64.whl", hash = "sha256:3b81f08d6052ac74f479215029e253d88fb80e9867e8bc034252d345abfa94ce", size = 1292003, upload-time = "2026-11-06T09:53:14.207Z" }, + { url = "https://files.pythonhosted.org/packages/0b/b9/9d18977c7ec9fa0d0fb22f0e52b3a270fef7b8251579d46660fca285e289/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:a51297c26ab637a97ec3283a39de163efce0a926d0ccd4378faabf5994adb01f", size = 1331925, upload-time = "2026-11-06T09:54:53.632Z" }, + { url = "https://files.pythonhosted.org/packages/ff/af/a86d51e4550c92a794777a59a9332d135c975c6f6c25b7506c447c3be27e/hypothesis-6.170.15-cp315-abi3.abi3t-win32.whl", hash = "sha256:51246e702c458b42a4b5079c3e6904c9dfb5193de920ed91fdbfa09fa694c55b", size = 685060, upload-time = "2026-11-06T09:53:35.48Z" }, + { url = "https://files.pythonhosted.org/packages/dc/3d/ef64b33ef8c5eceb7448860b77bc1d28e3e3b3e92b7d662456fee227f4b0/hypothesis-6.170.15-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:a951de05b61b7c1235a732543dc6c3b105b6c894e736f21cb891449589aaeba7", size = 691031, upload-time = "2026-11-06T09:53:10.201Z" }, + { url = "https://files.pythonhosted.org/packages/e8/3d/f875573e232550be631b6932f93bd6b2234d880891394fe4d70d57e292b7/hypothesis-6.170.15-cp315-abi3.abi3t-win_arm64.whl", hash = "sha256:9dc31166ccb95928c6eb05817684b2dd1c2a3698a6daad0450e5f449e44bb633", size = 689008, upload-time = "2026-11-06T09:54:13.194Z" }, + { url = "https://files.pythonhosted.org/packages/4d/f4/34e1ca38f88cbf478f970b7743ea022e0d70d5b4e943eea7c06532aea6b0/hypothesis-6.170.15-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:bfe10cd8c8138ba84cdd0f72d72e0a85f0f9adea8bc730f4ab4676cd41a730af", size = 801079, upload-time = "2026-11-06T09:53:19.956Z" }, + { url = "https://files.pythonhosted.org/packages/6d/8b/3438b357b3f6e076ff3f68aee5a62c1319573c4858b9f9db6e12e2893fca/hypothesis-6.170.15-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:5c1331070d8688d31b9ce99a100593bc6afdada964689b5e1a5f2ecffefa2455", size = 795993, upload-time = "2026-11-06T09:54:52.505Z" }, + { url = "https://files.pythonhosted.org/packages/fb/a7/f25cc6ec59659ef59093ffa743a2494cc153bb8a8eeeb78e1c1e58720888/hypothesis-6.170.15-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b56ea17542eabcb9e2c1d574fcabc9df7e14a7376cfce324e2fa05e9c836fff8", size = 1125066, upload-time = "2026-11-06T09:54:19.213Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c3/4b58275fe5771859bd03fe5ceccee64968874fdb999c549abf7ae7f716b9/hypothesis-6.170.15-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1c3b98713318639a6c852f3fff60bddd466096528eb2cd5853ab077ef04f74c", size = 1168451, upload-time = "2026-11-06T09:53:38.214Z" }, + { url = "https://files.pythonhosted.org/packages/dd/b8/c935e11303f94a6e280e059aedc7c5a6458207f7039aa241d2504e178c53/hypothesis-6.170.15-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:7ea75bc4c55f0ebb80179ae7e8fe1c8ab09b553005d1aadcec14e97e1306a82a", size = 694365, upload-time = "2026-11-06T09:53:59.021Z" }, + { url = "https://files.pythonhosted.org/packages/3b/54/ab7c9a7581b0acaeb58850629f4772aab054f2fd6a77bd3264262dfb1156/hypothesis-6.170.15-pp312-pypy312_pp80-macosx_10_12_x86_64.whl", hash = "sha256:45c267cb5bcd7b73b1ca6cedb039de423b8695b34a31cc87c29a7787058e7e59", size = 801399, upload-time = "2026-11-06T09:54:10.562Z" }, + { url = "https://files.pythonhosted.org/packages/fe/a6/a7dfce075d7371c9951e2a69e78d93bff5099d1b7b0ca207497eed68428b/hypothesis-6.170.15-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:3eb9428e0ba92993b61cab0289b8450f469b1e4c56cbdbdeaad258f0fb4f107e", size = 793309, upload-time = "2026-11-06T09:53:07.629Z" }, + { url = "https://files.pythonhosted.org/packages/6f/b4/ce76691a588dca99c73116593b2514af2d0095e7e72d3bcdfb7dcecf2170/hypothesis-6.170.15-pp312-pypy312_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9c30c911be51aa4fa84706f1d79dcd9ad6b9728207e69667a3fed2d4ab711434", size = 1123240, upload-time = "2026-11-06T09:53:44.286Z" }, + { url = "https://files.pythonhosted.org/packages/52/a7/998ba78de4842158178f6d96eca52ec1c786548b3e08902d527469329c04/hypothesis-6.170.15-pp312-pypy312_pp80-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d2b68004bd5a238320569f7c03322b22815c2c145b1f7bbf52a319662570ee5c", size = 1167454, upload-time = "2026-11-06T09:54:48.426Z" }, + { url = "https://files.pythonhosted.org/packages/03/f5/410ff24a49dd645f651732f45e466cbb73f4bb73d1c54eaa5a07b832b0a2/hypothesis-6.170.15-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:d25e9a3f92e9f824bb110679506ece2b8fd7d093f1fa7d819ca46278a681a1f1", size = 692539, upload-time = "2026-11-06T09:53:30.812Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, +] + +[[package]] +name = "obstore" +version = "0.12.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/c5/9fbb70a0914f4cd5ee7f0fd3e39e0812c29cdb4b4a8120ac7870f379e8a0/obstore-0.12.1.tar.gz", hash = "sha256:80549c9ea5478fd5d5bd75a3c9178841c7108a76d8139db05407a25a55a6a476", size = 138207, upload-time = "2026-10-27T22:51:02.613Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f7/ed/9667a1b1c6022b212460210929cc2b89bd72883c1182c9ea513a228158ad/obstore-0.12.1-cp311-abi3-macosx_10_12_x86_64.whl", hash = "sha256:8c97afecce59224b82fcb4588a3d6fbef479bd6cc2616b8f4d3d3ddba43fa6b7", size = 5431853, upload-time = "2026-10-27T22:49:38.938Z" }, + { url = "https://files.pythonhosted.org/packages/c9/bf/78437ef20196862b6f77f112184ca6c14783ddb98eb601fea88ee07c7acb/obstore-0.12.1-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:60af5d92da9332014bba8d34f985b9dc692e73d1141d1775dd3a328db476f219", size = 4592428, upload-time = "2026-10-27T22:49:40.799Z" }, + { url = "https://files.pythonhosted.org/packages/f5/30/80f63a19ace4d55ee94b7572dacf5435aeaa835e32550277c9b630fa6974/obstore-0.12.1-cp311-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:cf96279d243efd65d005c992e20476b3f343a54f71416d04af5d29d9998e739b", size = 5029909, upload-time = "2026-10-27T22:49:42.497Z" }, + { url = "https://files.pythonhosted.org/packages/07/43/4943fd0e5f89db060511a7e96ac887502f8d682b044e70b8e96f7f5bbf41/obstore-0.12.1-cp311-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5b22ca0d66af4c3dd130ed492f966eb7d775529ea129bf379d002dd2c4093971", size = 5276990, upload-time = "2026-10-27T22:49:44.028Z" }, + { url = "https://files.pythonhosted.org/packages/39/85/374b2f8356f052c058be845dbd4e5930d952636bb54dde67e3219ad52689/obstore-0.12.1-cp311-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b9ad04de828d3726da251b95ac7cf5bf4397c026243bb88b2d087e4ca1d7506c", size = 5445620, upload-time = "2026-10-27T22:49:45.634Z" }, + { url = "https://files.pythonhosted.org/packages/df/b7/1b8c950cc7cdadb65eace8d8c7a3e53b45341b726a28a3f93d2e2db98e75/obstore-0.12.1-cp311-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:437831889a617deb632b54be8e978b59db5c34e57f7329dd5ced1f2ee2895473", size = 5355053, upload-time = "2026-10-27T22:49:47.206Z" }, + { url = "https://files.pythonhosted.org/packages/9f/de/dc6eb84ef8d1f96af626c83b3da436b1a4d6b89aa52b560d4451f9ca8ef8/obstore-0.12.1-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d31b255aec88d37636d374a651f5efc684c89716ab64dea6ac89d75801933af2", size = 5591012, upload-time = "2026-10-27T22:49:48.912Z" }, + { url = "https://files.pythonhosted.org/packages/81/b5/f327b606c3aa1c7cc78f7595da7df96d8751e69912afa6331b48234098b6/obstore-0.12.1-cp311-abi3-manylinux_2_24_aarch64.whl", hash = "sha256:d7ee9cde74dbe11a4630c90d7245543993f3cebc38a70aceaedcd3b3d6192807", size = 5376219, upload-time = "2026-10-27T22:49:50.393Z" }, + { url = "https://files.pythonhosted.org/packages/22/f2/54890109d9c1c8ed16d3ad8b17f53953e04006d6b1bf013e13c56c7ef979/obstore-0.12.1-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:4240e5cb60d091e4a612499630eebede5164c821196322bc8a5ecb4861dc7b1f", size = 5570174, upload-time = "2026-10-27T22:49:51.889Z" }, + { url = "https://files.pythonhosted.org/packages/1a/e4/8573194930c7a8cf4354b894dfd3a40ad94e9c33b5e6c88213da7038a630/obstore-0.12.1-cp311-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:7b8e376fb425cd3963bbc2d51c0e0f19bebdaf3f824ffdac9bfc8dc13a782b5b", size = 5257775, upload-time = "2026-10-27T22:49:53.573Z" }, + { url = "https://files.pythonhosted.org/packages/6d/0d/9b3ec1f0c054b104ebf00333dc8f69f56c023c4f466fb09c52ccd25501a7/obstore-0.12.1-cp311-abi3-musllinux_1_2_i686.whl", hash = "sha256:2fcec4ccfeac0c5ad43c184692f60d15b79e8db594b075c45a40c5f7eeab9276", size = 5403147, upload-time = "2026-10-27T22:49:55.245Z" }, + { url = "https://files.pythonhosted.org/packages/b9/57/834fe762603c42d70957699d5fa84ccb51c812abc60f22a70cd56ac1a0fb/obstore-0.12.1-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:656547972c57aee8054fedd2585f4280d50bc8fee192269367547c4a01759d2f", size = 5821292, upload-time = "2026-10-27T22:49:56.895Z" }, + { url = "https://files.pythonhosted.org/packages/6d/a8/1e71da6cc12d4df8da701defd2ee78edfa5298f8eddfceb6b491a9c7b4aa/obstore-0.12.1-cp311-abi3-win_amd64.whl", hash = "sha256:d84cdaeeb5f45bfa685fef3ec87265b48af13f8d006ca7c5ed1424c91e448dd5", size = 5343080, upload-time = "2026-10-27T22:49:58.631Z" }, + { url = "https://files.pythonhosted.org/packages/3e/39/6bb0099a1002498743a9aff82b6e5abbf07d0ac8ed672080374a3528b16a/obstore-0.12.1-cp311-abi3-win_arm64.whl", hash = "sha256:6eaf07332b1121dcb3b401da9220b22f94d8e3823f2cdc69e4d8b13c4adba0a6", size = 5155426, upload-time = "2026-10-27T22:50:00.462Z" }, + { url = "https://files.pythonhosted.org/packages/b7/cd/ca597f403114ca8cf0f46fb15db1db68b2c04bd14203a21d8eb5491688d5/obstore-0.12.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:5a8dec8c89d710ba0debc7a9e7a3d56bb207f32d6acb0dc95f786c19aa4a811f", size = 5443755, upload-time = "2026-10-27T22:50:02.018Z" }, + { url = "https://files.pythonhosted.org/packages/d4/36/42c26efb568b1a386f279dcb26d05df04243dacc5f4123108790390a3c00/obstore-0.12.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:850062a27e9162c6bb9c4e18f539a693531df741b6c5fd5d8b2a17a8c4681dda", size = 4562659, upload-time = "2026-10-27T22:50:04.262Z" }, + { url = "https://files.pythonhosted.org/packages/d2/29/341473d040251cd4918204315cbc00b0bdc9ed94e89eb3ceacd4b4b75ad9/obstore-0.12.1-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de9eb44136babc4eccdb96e5d04f195612b976f6e708573a127b2ac46eeb0b49", size = 5423989, upload-time = "2026-10-27T22:50:05.848Z" }, + { url = "https://files.pythonhosted.org/packages/13/5e/febe7b32fc416128d61e18c86fd5da7adf8be22b1bf0be1d94e8622a197e/obstore-0.12.1-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ee8a1d6619ad9db9a84b1e7b769f639d16f7122255e48fec475d93f00d1206f3", size = 5353082, upload-time = "2026-10-27T22:50:07.416Z" }, + { url = "https://files.pythonhosted.org/packages/47/55/926becb2372bc22af0aa0c9aad61dcdd9af29bae942a36951c622f167c63/obstore-0.12.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8806b2e4a46a8ae69b1af7187d5bb9a0f1c717583c5525e7eccdf9b7e76da475", size = 5575137, upload-time = "2026-10-27T22:50:09.169Z" }, + { url = "https://files.pythonhosted.org/packages/f6/94/c7050bf30060fe8ea9523dc55a2d57b73dd5567abe62becaac7deba6b102/obstore-0.12.1-cp314-cp314t-manylinux_2_24_aarch64.whl", hash = "sha256:7880d391c3edf7abd6b1cb4c9071acd2c4ea108e4af83f57df4f351f4a5816bc", size = 5363584, upload-time = "2026-10-27T22:50:10.833Z" }, + { url = "https://files.pythonhosted.org/packages/e0/85/868d3589d761d5250724566f0dd942ac4b341279821cb8bddd62fe87416f/obstore-0.12.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:bf0131b338f5e23224d9009dd6f67b6088aeeeac80259ae32543f5653bce9ab1", size = 5561341, upload-time = "2026-10-27T22:50:12.609Z" }, + { url = "https://files.pythonhosted.org/packages/cb/78/ee95ddd84ecd492f132bd657f6d23761373eef496247fc1806bebfa02c3f/obstore-0.12.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8378a242379dc8f3955bf17847f22987348f2d978d0e5a43c15fff97a3c60989", size = 5804292, upload-time = "2026-10-27T22:50:14.14Z" }, + { url = "https://files.pythonhosted.org/packages/35/b1/1197446a6376c4297e162c6242dd01de7ea3419fa627cce6239cb01a8f6b/obstore-0.12.1-cp314-cp314t-win_amd64.whl", hash = "sha256:13f5a95b9722e4d489b9ac0a9d75d3e9d097ccde241cdfd6ca0150a3dd742619", size = 5320383, upload-time = "2026-10-27T22:50:16.004Z" }, + { url = "https://files.pythonhosted.org/packages/0e/da/34f86122a19ae305e58d2913b0eee7e777cc69283d5bc068590b6a8f68c6/obstore-0.12.1-cp314-cp314t-win_arm64.whl", hash = "sha256:31b5d33132e28f0933c3d35e9a1436a3b32ed68fd8bfa6e1d1b8ad69f7aa8d82", size = 5136428, upload-time = "2026-10-27T22:50:17.72Z" }, + { url = "https://files.pythonhosted.org/packages/00/2d/8c472ebe021c474c55ad79a8dfe3719281d1ac0592870d7fca8d92361461/obstore-0.12.1-cp315-abi3.abi3t-macosx_10_12_x86_64.whl", hash = "sha256:2da906fb0b5c28f6389a9561b96a5cc4da92f5eb9c2aeb3e2bd3768ab87e3717", size = 5491955, upload-time = "2026-10-27T22:50:19.814Z" }, + { url = "https://files.pythonhosted.org/packages/ce/c5/7a6cce169714f2a4c4aa90831f2c4015b07727eb8e17d858820ba70e4a81/obstore-0.12.1-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:4095f4e70ca24e8e7b1efeb87912cfc5142e2ec82888b1a63c0caa94fe875d22", size = 4608411, upload-time = "2026-10-27T22:50:21.49Z" }, + { url = "https://files.pythonhosted.org/packages/ab/9e/c0a2ab434103f89cfb0dcb3218e489273295936fdaa0b58fdef0d932aa77/obstore-0.12.1-cp315-abi3.abi3t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ab20d8a422a11b4236d4041861f52fa2e7e5b53fc80f2629c21fa3dd1e7fd8a1", size = 5059569, upload-time = "2026-10-27T22:50:23.035Z" }, + { url = "https://files.pythonhosted.org/packages/58/e9/d0c6db93119f0b18730d11f43ee46730c1c1031f35a742d99955fe8114c5/obstore-0.12.1-cp315-abi3.abi3t-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cf2c08fca6766f70a4d693e752fc279b57481e0a9fbb6d86770f3eeea67ee7e8", size = 5289087, upload-time = "2026-10-27T22:50:24.627Z" }, + { url = "https://files.pythonhosted.org/packages/8a/13/f8ecff794eb93e13a749c4738cc39ffde2a227780676fc6b3e3e1874b953/obstore-0.12.1-cp315-abi3.abi3t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8a357ef92897cec37c6c4f630c71a8b5c3b602439bfeb7201c00682527526434", size = 5469409, upload-time = "2026-10-27T22:50:26.095Z" }, + { url = "https://files.pythonhosted.org/packages/1e/26/ad477c01bb505ba6ad648286e8ec89aab7290a089fc761d600c65609de33/obstore-0.12.1-cp315-abi3.abi3t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e422bf5821e5ceb8577154b62389b5b44136718f345db663bdd592d301aab1c0", size = 5390957, upload-time = "2026-10-27T22:50:28.009Z" }, + { url = "https://files.pythonhosted.org/packages/ab/cc/54242ed5d9f0b94631f686118292c639ba5824c7eb6fed7321fb52267523/obstore-0.12.1-cp315-abi3.abi3t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd80719105c062b941b172ffe758b8cebee7ab0526562793fb2e9d57961f8072", size = 5625205, upload-time = "2026-10-27T22:50:29.604Z" }, + { url = "https://files.pythonhosted.org/packages/a5/18/94263560896c75216c24295d1f6292180d9a006b94df9cfd45640af9fab5/obstore-0.12.1-cp315-abi3.abi3t-manylinux_2_24_aarch64.whl", hash = "sha256:fc673c165955d3b91fac276c8720daa10276f31d685f1e12fa16e4bb0144e82f", size = 5407054, upload-time = "2026-10-27T22:50:31.226Z" }, + { url = "https://files.pythonhosted.org/packages/fc/45/497e3a6de4cf78148fcffbd3bd3bc1272d9229feeece22e46db7927debfe/obstore-0.12.1-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6a019c276c606d930f5a7c538865186f9baa102019be0e24bfc94a8289a571eb", size = 5601269, upload-time = "2026-10-27T22:50:32.738Z" }, + { url = "https://files.pythonhosted.org/packages/4e/4f/6c0bc2a08bf6615417ad03cc3bf6a36da2e4e456ec7a0577803a8e934189/obstore-0.12.1-cp315-abi3.abi3t-musllinux_1_2_armv7l.whl", hash = "sha256:a83b1ee193c32f4da0473606ef32b9e4de924e00754c404e0ce9ff82f3076797", size = 5285684, upload-time = "2026-10-27T22:50:34.304Z" }, + { url = "https://files.pythonhosted.org/packages/87/1f/b21fa2caaed5050c0622dc0ae5ccf5dc907a4ea33cf03d1f921734cc5828/obstore-0.12.1-cp315-abi3.abi3t-musllinux_1_2_i686.whl", hash = "sha256:8ed7826686178130f5f131e7b2d435f24f1256bf44029d4fb29ff1fca441c008", size = 5412047, upload-time = "2026-10-27T22:50:35.768Z" }, + { url = "https://files.pythonhosted.org/packages/ab/a0/989bb53ab9371959aa8923598520ff17f30e43b2e790d0a1e0cc5afb50f0/obstore-0.12.1-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:6e8b45d1ceed62706c0e19680a6cb705d9094d550e7f1287e230a86694a7c5c6", size = 5853753, upload-time = "2026-10-27T22:50:37.568Z" }, + { url = "https://files.pythonhosted.org/packages/4a/95/86c53a2d63dd3521fd895bf02a312893517f1489eaee837e7c1919b92f12/obstore-0.12.1-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:1b902e538809fd01e938707cc785e2efdfedc17600223323ef7b6a3d5c0874d9", size = 5365259, upload-time = "2026-10-27T22:50:39.099Z" }, + { url = "https://files.pythonhosted.org/packages/f1/6c/8a464c4d4a8ebce693e549777be90625cf01d0ba75daea99330d909d54a0/obstore-0.12.1-cp315-abi3.abi3t-win_arm64.whl", hash = "sha256:7c0497355e6fe55d98ef3fa94429488be9f2c4d26a786969f90a1e179efaa93a", size = 5179055, upload-time = "2026-10-27T22:50:41.339Z" }, + { url = "https://files.pythonhosted.org/packages/0f/46/db83f5e902acc4d7188e828b52ff72e1072fcc92d56af1849fc3e3894350/obstore-0.12.1-pp311-pypy311_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:019af6060d0143975594a3f1efda0d15c0098702b889d048a2c085018a5c65e8", size = 5027315, upload-time = "2026-10-27T22:50:42.851Z" }, + { url = "https://files.pythonhosted.org/packages/ee/37/335aa42c62ce365b2ec37355f06eb6f57a8b53aa99160f0babec7c593e63/obstore-0.12.1-pp311-pypy311_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8f7aeba8901b506056b01765e72d13af8a295ef1b64ad73251895364a843afef", size = 5278226, upload-time = "2026-10-27T22:50:44.413Z" }, + { url = "https://files.pythonhosted.org/packages/a4/e0/b3d447736a8e985ef10ffec4061bc895f2b410fe983b683213fec404ff0f/obstore-0.12.1-pp311-pypy311_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:bdbd3db63d7f97ada70ff9351948db6e4ba883ad189e422ffa03ff02dc4c34c4", size = 5440705, upload-time = "2026-10-27T22:50:45.952Z" }, + { url = "https://files.pythonhosted.org/packages/db/7b/cb10055c1f4cd78e3c52c5a43d912b3c1f5a6601d2989ea3656515061057/obstore-0.12.1-pp311-pypy311_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:96ce72f778133851d27602a429e744620ea6e762630a5f58140bb4f71fdaf8be", size = 5353724, upload-time = "2026-10-27T22:50:47.409Z" }, + { url = "https://files.pythonhosted.org/packages/6c/bd/bb2a98c22191b29f02c042e98be026a13e7eb284531f64d1a25a119ea6b4/obstore-0.12.1-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ca9a0399a5b43de54a31777cc56f8f2f7893ac444cac2b7d834f2bea299cad61", size = 5586399, upload-time = "2026-10-27T22:50:48.973Z" }, + { url = "https://files.pythonhosted.org/packages/e7/48/e0d510abfba83e571529b892e0d54280828b2761e6409af34b811cca58aa/obstore-0.12.1-pp311-pypy311_pp73-manylinux_2_24_aarch64.whl", hash = "sha256:5c1fe53af794af798ac1e0ec509a0cbfc66fe68df98d3cc1b557d4602dd39b50", size = 5375790, upload-time = "2026-10-27T22:50:50.884Z" }, + { url = "https://files.pythonhosted.org/packages/0f/0a/c5999ce2d5d70071d2e6b45b10c98bc22bb5427d84120f02ca94b1716c7d/obstore-0.12.1-pp311-pypy311_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:f7e02534dfcc2fd6188a4aa5901bafcf032142fbf8836caab80db7b6ad25e369", size = 5569722, upload-time = "2026-10-27T22:50:52.507Z" }, + { url = "https://files.pythonhosted.org/packages/f6/61/b899283be0df446f3f9cb2815a64d9faf8a8b30487954795b92471d3e90b/obstore-0.12.1-pp311-pypy311_pp73-musllinux_1_2_armv7l.whl", hash = "sha256:eea60451265e609c48510787080a403b79144a45e69f59b330f7e3901e11236f", size = 5252932, upload-time = "2026-10-27T22:50:54.126Z" }, + { url = "https://files.pythonhosted.org/packages/04/36/daed807520fdab5ac0031e0d7a459b3ce5aedde21f2f315b278c369599dc/obstore-0.12.1-pp311-pypy311_pp73-musllinux_1_2_i686.whl", hash = "sha256:f4cedcc164644f2923b19a763aa07a04134072bbf7a190637c267072cd8f6e4d", size = 5398228, upload-time = "2026-10-27T22:50:55.92Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e0/6e38c19d1fd4dc40f087ad953c2c0dea1203994d359f253e1123ae175351/obstore-0.12.1-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:94fba14cd7d64f7a0b4da0224dcaec9c379ba7a1ddcad2c5e4c35a0b56977b61", size = 5815556, upload-time = "2026-10-27T22:50:57.387Z" }, + { url = "https://files.pythonhosted.org/packages/d8/c6/f0b45052e07d8eb2f5a6836b45babf18b06dae2019404f9af4662db6666c/obstore-0.12.1-pp311-pypy311_pp80-macosx_10_12_x86_64.whl", hash = "sha256:2edaecb8b06e6f1674f8e0375f0e25df00c4a2162c489769cd4ffc182e8069ba", size = 5424080, upload-time = "2026-10-27T22:50:58.899Z" }, + { url = "https://files.pythonhosted.org/packages/d3/b5/91046acc476a58c02731140d987cc3faed8a4dd073154b9c3eaf34965107/obstore-0.12.1-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:eb4fcec7658aa6929f77502edef424213db8dfe173276ae6bff67df8f95e5aff", size = 4591674, upload-time = "2026-10-27T22:51:00.972Z" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "pluggy" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, +] + +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + +[[package]] +name = "pytest" +version = "9.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/79/42/bb4641652e58dedeac2ec51abc1f8cae4fee4ec63899a0999016229a0f2a/pytest-9.2.0.tar.gz", hash = "sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b", size = 1797555, upload-time = "2026-10-27T21:30:20.728Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" }, +] + +[[package]] +name = "sortedcontainers" +version = "2.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e8/c4/ba2f8066cceb6f23394729afe52f3bf7adec04bf9ed2c820b39e19299111/sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88", size = 30594, upload-time = "2021-05-16T22:03:42.897Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0", size = 29575, upload-time = "2021-05-16T22:03:41.177Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "zarr-storage" +source = { editable = "." } +dependencies = [ + { name = "typing-extensions" }, +] + +[package.optional-dependencies] +obstore = [ + { name = "obstore" }, +] +testing = [ + { name = "hypothesis" }, + { name = "pytest" }, +] + +[package.dev-dependencies] +test = [ + { name = "hypothesis" }, + { name = "obstore" }, + { name = "pytest" }, +] + +[package.metadata] +requires-dist = [ + { name = "hypothesis", marker = "extra == 'testing'", specifier = ">=6.85" }, + { name = "obstore", marker = "extra == 'obstore'", specifier = ">=0.12" }, + { name = "pytest", marker = "extra == 'testing'", specifier = ">=8" }, + { name = "typing-extensions", specifier = ">=4.6" }, +] +provides-extras = ["obstore", "testing"] + +[package.metadata.requires-dev] +test = [ + { name = "hypothesis", specifier = ">=6.85" }, + { name = "obstore", specifier = ">=0.12" }, + { name = "pytest", specifier = ">=8" }, +] From ac6ac50892eca07d424b90c88726db2a2a2b119e Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 17 Nov 2026 16:21:10 +0100 Subject: [PATCH 02/31] docs(zarr-storage): add changelog fragment Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-storage/changes/460.feature.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 packages/zarr-storage/changes/460.feature.md diff --git a/packages/zarr-storage/changes/460.feature.md b/packages/zarr-storage/changes/460.feature.md new file mode 100644 index 0000000000..c6bd9979d3 --- /dev/null +++ b/packages/zarr-storage/changes/460.feature.md @@ -0,0 +1 @@ +Add `zarr-storage`, a new package with a Zarr-agnostic key-value storage API: a `Store` view over memory, local-filesystem and obstore backends, with sync and async methods, conditional writes, byte-range reads and reads into caller buffers. It ships a conformance suite in `zarr_storage.testing` that any backend can run. From 10a4262cefaf095a030a16e0e77d3d095be79600 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 17 Nov 2026 16:40:51 +0100 Subject: [PATCH 03/31] feat(zarr-storage)!: return closed result unions and split conditional operations Reads return `Found | Missing` (and `FoundRanges`, `Copied`) instead of `ReadResult | None`, so a missing key is a value an HTTP 404 maps onto. `get_if_changed` adds conditional reads that return `Unchanged` without reading bytes (HTTP 304, obstore `If-None-Match`). Conditional writes become their own methods: `put` returns `Written`, `put_if_absent` returns `Written | Rejected`, `put_if_match` and `delete_if_match` live in the `WritableIfMatch` and `DeletableIfMatch` capability protocols. Each method returns only the outcomes it can produce, and `delete_if_match` on an object store is now a type error rather than a runtime refusal. Backends share one implementation per operation, parameterized by a precondition function. Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-storage/DESIGN.md | 53 ++- packages/zarr-storage/changes/460.feature.md | 2 +- .../zarr-storage/src/zarr_storage/__init__.py | 32 +- .../src/zarr_storage/_protocols.py | 103 +++-- .../zarr-storage/src/zarr_storage/_store.py | 209 +++++----- .../zarr-storage/src/zarr_storage/_types.py | 82 ++-- .../src/zarr_storage/backends/_common.py | 38 +- .../src/zarr_storage/backends/_local.py | 171 +++++--- .../src/zarr_storage/backends/_memory.py | 142 ++++--- .../src/zarr_storage/backends/_obstore.py | 380 +++++++++++------- .../src/zarr_storage/testing/__init__.py | 4 +- .../src/zarr_storage/testing/_api.py | 115 ++++-- .../src/zarr_storage/testing/_stateful.py | 82 ++-- .../src/zarr_storage/testing/_suite.py | 281 +++++++------ packages/zarr-storage/tests/test_local.py | 36 +- packages/zarr-storage/tests/test_obstore.py | 28 +- packages/zarr-storage/tests/test_store.py | 30 +- 17 files changed, 1149 insertions(+), 639 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index c78c639127..51a2559fa4 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -13,8 +13,10 @@ Sources, and what each contributed: 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. -- **zarr-python-planning store proposals**: `ReadResult`/`PutResult`/`ObjectMetadata`, conditional - writes that report `applied=False` instead of raising, the conformance-suite layout. +- **zarr-python-planning 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`). - **The storage plan**: 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 @@ -29,8 +31,8 @@ Store one concrete class: (backend, root, read_only, owner); validates keys, relativizes listings, enforces read-only; `store / "a"` is a view on the same backend ``` -A **backend** is an object that implements some capability protocols (`Read`, `Write`, `List`, and their -async twins) on *backend paths*: `/`-separated strings, already joined with the root. Backends never +A **backend** is an object that implements some capability protocols (`Readable`, `Writable`, +`Listable`, `WritableIfMatch`, `DeletableIfMatch`, and their async twins) on *backend paths*: `/`-separated strings, already joined with the root. Backends never see relative keys and never join or strip paths. They hold everything that must exist once: the dict, the filesystem root, a client, locks, concurrency limits. @@ -55,16 +57,30 @@ get them wrong on its own (the source of most bugs in the legacy API: #2190, #24 | Method | Returns | Notes | |---|---|---| -| `get(key, *, byte_range=None)` | `ReadResult \| None` | `None` when the key is missing (zarrs, TensorStore). Conditional reads (`if_not_match`) arrive with caching in iteration 3 | -| `get_ranges(key, ranges)` | `RangesResult \| None` | 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)` | `int \| None` | bytes written into `out`, any writable C-contiguous buffer; `ValueError` if it is too small, read-only or not contiguous | -| `head(key)` | `ObjectMetadata \| None` | size, generation, last-modified | -| `put(key, value, *, if_match=None, if_none_match=False)` | `PutResult` | `value` is any C-contiguous buffer, copied; a failed precondition returns `applied=False`, it doesn't raise; `KeyConflictError` where the backend can't hold a key and a directory with one name | -| `delete(key, *, if_match=None)` | `DeleteResult` | one key; deleting a directory name deletes nothing | +| `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` | `Copied.size` bytes written into `out`, any writable C-contiguous buffer; `ValueError` if it is too small, read-only or not contiguous | +| `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 | | `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. + Listing arguments are checked when the method is called; the items are produced lazily, and taking one after the store closes raises `StoreClosedError`. @@ -95,11 +111,13 @@ key (`a/b` when `a` is a key): that reads as absent. ## Backends -| Backend | Generations | Conditional `put` / `delete` | Key and directory with one name | Pickles | +| 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 / no | as the store does | as the store does | +| `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` 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 @@ -111,7 +129,8 @@ every concurrent write). A later write of a key with such a directory's name rec raises `KeyConflictError`, whatever its preconditions. A symlink in a key's place is that key's file. 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, conditional writes raise `UnsupportedOperationError`. +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. `ObjectStoreBackend.get_ranges` reads the first range unpinned, takes the generation and size from @@ -130,9 +149,11 @@ as mixins a backend's test class adds (`ConditionalPutSuite`, `KeyAndDirectorySu `KeyDirectoryConflictSuite`, `ConditionalRaceSuite`, ...). Every test runs twice: through the sync methods, and through the async methods on one event loop, so the two surfaces meet one contract. -`StoreSuite.test_state_machine` drives random sequences of puts, conditional puts, deletes, -conditional deletes, `delete_dir` and listings through random views, and checks every step against a -dict model (`zarr_storage.testing._stateful.StoreMachine`), again through both surfaces. The obstore +`StoreSuite.test_state_machine` drives random sequences of `put`, `put_if_absent`, `put_if_match`, +`delete`, `delete_if_match`, `delete_dir` and listings through random views, and checks every step against a +dict model (`zarr_storage.testing._stateful.StoreMachine`), again through both surfaces. After every +step, each stored key reads back as the model says, and `get_if_changed` with its generation is +`Unchanged`. The obstore tests also fail any async run that makes a blocking obstore call. ## Configuration diff --git a/packages/zarr-storage/changes/460.feature.md b/packages/zarr-storage/changes/460.feature.md index c6bd9979d3..8195140b25 100644 --- a/packages/zarr-storage/changes/460.feature.md +++ b/packages/zarr-storage/changes/460.feature.md @@ -1 +1 @@ -Add `zarr-storage`, a new package with a Zarr-agnostic key-value storage API: a `Store` view over memory, local-filesystem and obstore backends, with sync and async methods, conditional writes, byte-range reads and reads into caller buffers. It ships a conformance suite in `zarr_storage.testing` that any backend can run. +Add `zarr-storage`, a new package with a Zarr-agnostic key-value storage API: a `Store` view over memory, local-filesystem and obstore backends, with sync and async methods, conditional reads and writes (`get_if_changed`, `put_if_absent`, `put_if_match`, `delete_if_match`), byte-range reads and reads into caller buffers. It ships a conformance suite in `zarr_storage.testing` that any backend can run. diff --git a/packages/zarr-storage/src/zarr_storage/__init__.py b/packages/zarr-storage/src/zarr_storage/__init__.py index 9bcbaf477a..2b4443c06c 100644 --- a/packages/zarr-storage/src/zarr_storage/__init__.py +++ b/packages/zarr-storage/src/zarr_storage/__init__.py @@ -16,6 +16,8 @@ ) from zarr_storage._protocols import ( Backend, + DeletableIfMatch, + DeletableIfMatchAsync, Listable, ListableAsync, Readable, @@ -24,30 +26,41 @@ ReadableIntoAsync, Writable, WritableAsync, + WritableIfMatch, + WritableIfMatchAsync, ) from zarr_storage._store import Store from zarr_storage._types import ( ByteRange, - DeleteResult, + Copied, + Deleted, Entry, + Found, + FoundRanges, Generation, Key, ListItem, + Missing, ObjectMetadata, OffsetRequest, Prefix, - PutResult, RangeRequest, - RangesResult, - ReadResult, + Rejected, SuffixRequest, + Unchanged, + Written, ) __all__ = [ "Backend", "ByteRange", - "DeleteResult", + "Copied", + "DeletableIfMatch", + "DeletableIfMatchAsync", + "Deleted", "Entry", + "Found", + "FoundRanges", "Generation", "InvalidByteRangeError", "InvalidKeyError", @@ -56,23 +69,26 @@ "ListItem", "Listable", "ListableAsync", + "Missing", "ObjectMetadata", "OffsetRequest", "Prefix", - "PutResult", "RangeRequest", - "RangesResult", "ReadOnlyError", - "ReadResult", "Readable", "ReadableAsync", "ReadableInto", "ReadableIntoAsync", + "Rejected", "StorageError", "Store", "StoreClosedError", "SuffixRequest", + "Unchanged", "UnsupportedOperationError", "Writable", "WritableAsync", + "WritableIfMatch", + "WritableIfMatchAsync", + "Written", ] diff --git a/packages/zarr-storage/src/zarr_storage/_protocols.py b/packages/zarr-storage/src/zarr_storage/_protocols.py index 9f1db360a5..44ae50fa9d 100644 --- a/packages/zarr-storage/src/zarr_storage/_protocols.py +++ b/packages/zarr-storage/src/zarr_storage/_protocols.py @@ -9,7 +9,8 @@ Each capability has a sync protocol and an async twin whose methods end in `_async`. A backend implements whichever it can; `Store`'s methods are typed so that calling one the backend lacks is a -type error. +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`. """ from __future__ import annotations @@ -21,17 +22,23 @@ from zarr_storage._types import ( ByteRange, - DeleteResult, + Copied, + Deleted, + Found, + FoundRanges, Generation, ListItem, + Missing, ObjectMetadata, - PutResult, - RangesResult, - ReadResult, + Rejected, + Unchanged, + Written, ) __all__ = [ "Backend", + "DeletableIfMatch", + "DeletableIfMatchAsync", "Listable", "ListableAsync", "Readable", @@ -40,6 +47,8 @@ "ReadableIntoAsync", "Writable", "WritableAsync", + "WritableIfMatch", + "WritableIfMatchAsync", ] @@ -62,22 +71,30 @@ def close(self) -> None: class Readable(Backend, Protocol): - def get(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: - """The value at `path`, or the requested part of it; `None` if the key is absent.""" + def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + """The value at `path`, or the requested part of it.""" ... - def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: - """Several parts of the value at `path`, from one read; `None` if the key is absent.""" + 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 head(self, path: str) -> ObjectMetadata | None: - """The size and generation of the value at `path`; `None` if the key is absent.""" + 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): - def get_into(self, path: str, out: memoryview, byte_range: ByteRange | None) -> int | None: - """Copy the value (or part) into `out`; the number of bytes, or `None` if absent. + def get_into( + self, path: str, out: memoryview, byte_range: ByteRange | None + ) -> Copied | Missing: + """Copy the value (or part) into `out`. Raises `ValueError` if `out` is shorter than the bytes to copy. """ @@ -85,14 +102,16 @@ def get_into(self, path: str, out: memoryview, byte_range: ByteRange | None) -> class Writable(Backend, Protocol): - def put( - self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool - ) -> PutResult: - """Write `value` at `path`, if the preconditions hold.""" + 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, *, if_match: Generation | None) -> DeleteResult: - """Delete the key at `path`, if the precondition holds. A directory is not a key.""" + 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: @@ -100,6 +119,20 @@ def delete_dir(self, directory: str) -> None: ... +class WritableIfMatch(Backend, Protocol): + 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): + def delete_if_match(self, path: str, generation: Generation) -> Deleted | Rejected | Missing: + """Delete the key at `path` if its value has `generation`.""" + ... + + class Listable(Backend, Protocol): def list(self, directory: str) -> Iterator[str]: """Every key under `directory`, as backend paths, in no particular order.""" @@ -111,31 +144,47 @@ def list_dir(self, directory: str) -> Iterator[ListItem]: class ReadableAsync(Backend, Protocol): - async def get_async(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: ... + 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] - ) -> RangesResult | None: ... + ) -> FoundRanges | Missing: ... - async def head_async(self, path: str) -> ObjectMetadata | None: ... + async def head_async(self, path: str) -> ObjectMetadata | Missing: ... class ReadableIntoAsync(Backend, Protocol): async def get_into_async( self, path: str, out: memoryview, byte_range: ByteRange | None - ) -> int | None: ... + ) -> Copied | Missing: ... class WritableAsync(Backend, Protocol): - async def put_async( - self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool - ) -> PutResult: ... + 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, *, if_match: Generation | None) -> DeleteResult: ... + async def delete_async(self, path: str) -> Deleted | Missing: ... async def delete_dir_async(self, directory: str) -> None: ... +class WritableIfMatchAsync(Backend, Protocol): + async def put_if_match_async( + self, path: str, value: memoryview, generation: Generation + ) -> Written | Rejected | Missing: ... + + +class DeletableIfMatchAsync(Backend, Protocol): + async def delete_if_match_async( + self, path: str, generation: Generation + ) -> Deleted | Rejected | Missing: ... + + class ListableAsync(Backend, Protocol): def list_async(self, directory: str) -> AsyncIterator[str]: ... diff --git a/packages/zarr-storage/src/zarr_storage/_store.py b/packages/zarr-storage/src/zarr_storage/_store.py index 489d130b32..b5d679c9bd 100644 --- a/packages/zarr-storage/src/zarr_storage/_store.py +++ b/packages/zarr-storage/src/zarr_storage/_store.py @@ -13,12 +13,15 @@ from zarr_storage._errors import ReadOnlyError, StoreClosedError from zarr_storage._keys import check_key, is_within, join, normalize_directory, relativize from zarr_storage._protocols import Backend +from zarr_storage._types import Copied, Found, Missing if TYPE_CHECKING: from collections.abc import AsyncIterator, Iterator, Sequence from types import TracebackType from zarr_storage._protocols import ( + DeletableIfMatch, + DeletableIfMatchAsync, Listable, ListableAsync, Readable, @@ -27,16 +30,19 @@ ReadableIntoAsync, Writable, WritableAsync, + WritableIfMatch, + WritableIfMatchAsync, ) from zarr_storage._types import ( ByteRange, - DeleteResult, + Deleted, + FoundRanges, Generation, ListItem, ObjectMetadata, - PutResult, - RangesResult, - ReadResult, + Rejected, + Unchanged, + Written, ) __all__ = ["Store"] @@ -207,76 +213,84 @@ def _writable_directory(self, directory: str) -> str: def get( self: Store[Readable], key: str, *, byte_range: ByteRange | None = None - ) -> ReadResult | None: - """The value at `key`, or the part `byte_range` selects; `None` if the key is absent.""" + ) -> Found | Missing: + """The value at `key`, or the part `byte_range` selects.""" return self._backend.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. + """ + return self._backend.get_if_changed(self._path(key), generation, byte_range) + def get_ranges( self: Store[Readable], key: str, ranges: Sequence[ByteRange] - ) -> RangesResult | None: - """Several parts of the value at `key` from one read; `None` if the key is absent.""" + ) -> FoundRanges | Missing: + """Several parts of the value at `key`, all from one generation.""" return self._backend.get_ranges(self._path(key), ranges) def get_into( - self: Store[Readable], - key: str, - out: Buffer, - *, - byte_range: ByteRange | None = None, - ) -> int | None: + self: Store[Readable], key: str, out: Buffer, *, byte_range: ByteRange | None = None + ) -> Copied | Missing: """Copy the value at `key` (or part of it) into `out`. - Returns the number of bytes copied, or `None` if the key is absent. Raises `ValueError` if - `out` is shorter than the bytes to copy, read-only, or not C-contiguous. + Raises `ValueError` if `out` is shorter than the bytes to copy, read-only, or not + C-contiguous. """ path = self._path(key) view = _as_bytes_view(out, writable=True) if hasattr(self._backend, "get_into"): - return cast("ReadableInto", self._backend).get_into(path, view, byte_range) - result = self._backend.get(path, byte_range) - if result is None: - return None - return _copy_into(result.value, view) - - def head(self: Store[Readable], key: str) -> ObjectMetadata | None: - """The size and generation of the value at `key`; `None` if the key is absent.""" + backend = cast("ReadableInto", self._backend) + return backend.get_into(path, view, byte_range) + return _copy_into(self._backend.get(path, byte_range), view) + + def head(self: Store[Readable], key: str) -> ObjectMetadata | Missing: + """The size and generation of the value at `key`.""" return self._backend.head(self._path(key)) def exists(self: Store[Readable], key: str) -> bool: """Whether `key` holds a value.""" - return self.head(key) is not None + return not isinstance(self.head(key), Missing) # ----------------------------------------------------------------- sync writes - def put( - self: Store[Writable], - key: str, - value: Buffer, - *, - if_match: Generation | None = None, - if_none_match: bool = False, - ) -> PutResult: - """Write `value` at `key`. - - With `if_match`, write only if the key's current generation equals it. With - `if_none_match`, write only if the key is absent. A failed precondition returns - `PutResult(applied=False)`; it does not raise. + def put(self: Store[Writable], key: str, value: Buffer) -> Written: + """Write `value` at `key`.""" + return self._backend.put(self._writable_path(key), _as_bytes_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.""" + return self._backend.put_if_absent( + self._writable_path(key), _as_bytes_view(value, writable=False) + ) + + 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. """ - if if_match is not None and if_none_match: - raise ValueError("Pass at most one of if_match and if_none_match.") - path = self._writable_path(key) - return self._backend.put( - path, - _as_bytes_view(value, writable=False), - if_match=if_match, - if_none_match=if_none_match, + return self._backend.put_if_match( + self._writable_path(key), _as_bytes_view(value, writable=False), generation ) - def delete( - self: Store[Writable], key: str, *, if_match: Generation | None = None - ) -> DeleteResult: - """Delete the key `key`. A directory is not a key: deleting one deletes nothing.""" - return self._backend.delete(self._writable_path(key), if_match=if_match) + 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._backend.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`.""" + return self._backend.delete_if_match(self._writable_path(key), generation) def delete_dir(self: Store[Writable], directory: str = "") -> None: """Delete every key under `directory` (by default, every key in this store).""" @@ -305,68 +319,78 @@ def list_dir(self: Store[Listable], directory: str = "") -> Iterator[ListItem]: async def get_async( self: Store[ReadableAsync], key: str, *, byte_range: ByteRange | None = None - ) -> ReadResult | None: + ) -> Found | Missing: """Async `get`.""" return await self._backend.get_async(self._path(key), byte_range) + async def get_if_changed_async( + self: Store[ReadableAsync], + key: str, + generation: Generation, + *, + byte_range: ByteRange | None = None, + ) -> Found | Missing | Unchanged: + """Async `get_if_changed`.""" + return await self._backend.get_if_changed_async(self._path(key), generation, byte_range) + async def get_ranges_async( self: Store[ReadableAsync], key: str, ranges: Sequence[ByteRange] - ) -> RangesResult | None: + ) -> FoundRanges | Missing: """Async `get_ranges`.""" return await self._backend.get_ranges_async(self._path(key), ranges) async def get_into_async( - self: Store[ReadableAsync], - key: str, - out: Buffer, - *, - byte_range: ByteRange | None = None, - ) -> int | None: + self: Store[ReadableAsync], key: str, out: Buffer, *, byte_range: ByteRange | None = None + ) -> Copied | Missing: """Async `get_into`.""" path = self._path(key) view = _as_bytes_view(out, writable=True) if hasattr(self._backend, "get_into_async"): backend = cast("ReadableIntoAsync", self._backend) return await backend.get_into_async(path, view, byte_range) - result = await self._backend.get_async(path, byte_range) - if result is None: - return None - return _copy_into(result.value, view) + return _copy_into(await self._backend.get_async(path, byte_range), view) - async def head_async(self: Store[ReadableAsync], key: str) -> ObjectMetadata | None: + async def head_async(self: Store[ReadableAsync], key: str) -> ObjectMetadata | Missing: """Async `head`.""" return await self._backend.head_async(self._path(key)) async def exists_async(self: Store[ReadableAsync], key: str) -> bool: """Async `exists`.""" - return await self.head_async(key) is not None + return not isinstance(await self.head_async(key), Missing) # ----------------------------------------------------------------- async writes - async def put_async( - self: Store[WritableAsync], - key: str, - value: Buffer, - *, - if_match: Generation | None = None, - if_none_match: bool = False, - ) -> PutResult: + async def put_async(self: Store[WritableAsync], key: str, value: Buffer) -> Written: """Async `put`.""" - if if_match is not None and if_none_match: - raise ValueError("Pass at most one of if_match and if_none_match.") - path = self._writable_path(key) return await self._backend.put_async( - path, - _as_bytes_view(value, writable=False), - if_match=if_match, - if_none_match=if_none_match, + self._writable_path(key), _as_bytes_view(value, writable=False) + ) + + async def put_if_absent_async( + self: Store[WritableAsync], key: str, value: Buffer + ) -> Written | Rejected: + """Async `put_if_absent`.""" + return await self._backend.put_if_absent_async( + self._writable_path(key), _as_bytes_view(value, writable=False) + ) + + async def put_if_match_async( + self: Store[WritableIfMatchAsync], key: str, value: Buffer, generation: Generation + ) -> Written | Rejected | Missing: + """Async `put_if_match`.""" + return await self._backend.put_if_match_async( + self._writable_path(key), _as_bytes_view(value, writable=False), generation ) - async def delete_async( - self: Store[WritableAsync], key: str, *, if_match: Generation | None = None - ) -> DeleteResult: + async def delete_async(self: Store[WritableAsync], key: str) -> Deleted | Missing: """Async `delete`.""" - return await self._backend.delete_async(self._writable_path(key), if_match=if_match) + return await self._backend.delete_async(self._writable_path(key)) + + async def delete_if_match_async( + self: Store[DeletableIfMatchAsync], key: str, generation: Generation + ) -> Deleted | Rejected | Missing: + """Async `delete_if_match`.""" + return await self._backend.delete_if_match_async(self._writable_path(key), generation) async def delete_dir_async(self: Store[WritableAsync], directory: str = "") -> None: """Async `delete_dir`.""" @@ -389,12 +413,17 @@ async def _relativized(paths: AsyncIterator[str], root: str) -> AsyncIterator[st yield relativize(path, root) -def _copy_into(value: memoryview, out: memoryview) -> int: - 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 n +def _copy_into(result: Found | Missing, out: memoryview) -> Copied | Missing: + """The `get_into` outcome of a `get`, copying a found value into `out`.""" + 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 def _restore_store( diff --git a/packages/zarr-storage/src/zarr_storage/_types.py b/packages/zarr-storage/src/zarr_storage/_types.py index c527e8e77a..3c50860351 100644 --- a/packages/zarr-storage/src/zarr_storage/_types.py +++ b/packages/zarr-storage/src/zarr_storage/_types.py @@ -7,19 +7,23 @@ __all__ = [ "ByteRange", - "DeleteResult", + "Copied", + "Deleted", "Entry", + "Found", + "FoundRanges", "Generation", "Key", "ListItem", + "Missing", "ObjectMetadata", "OffsetRequest", "Prefix", - "PutResult", "RangeRequest", - "RangesResult", - "ReadResult", + "Rejected", "SuffixRequest", + "Unchanged", + "Written", ] Generation = NewType("Generation", object) @@ -80,47 +84,75 @@ def __post_init__(self) -> None: @dataclass(frozen=True, slots=True) -class ReadResult: - """The bytes a read returned, and the generation they belong to.""" +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 RangesResult: - """The bytes of several ranges of one value, all from one read of one generation.""" +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 PutResult: - """The outcome of a write. +class Copied: + """A read found the key and copied `size` bytes into the caller's buffer.""" - `applied` is `False` when a precondition (`if_match`, `if_none_match`) failed; `generation` is - then the key's current generation, or `None` if the key is absent. When `applied` is `True`, - `generation` is the generation of the value just written. + 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. """ - generation: Generation | None - applied: bool = True + read_at: float | None = None @dataclass(frozen=True, slots=True) -class DeleteResult: - """The outcome of a delete. - - | case | `generation` | `applied` | - |---|---|---| - | the key was absent | `None` | `False` | - | `if_match` did not match | the current generation | `False` | - | the key was deleted | the generation of the deleted value | `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 | None - applied: bool + generation: Generation @dataclass(frozen=True, slots=True) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_common.py b/packages/zarr-storage/src/zarr_storage/backends/_common.py index b6d63190e3..2cd5984317 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_common.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_common.py @@ -1,18 +1,48 @@ -"""Helpers shared by backends that hold a flat set of keys.""" +"""Helpers shared by backends: preconditions, and listing a flat set of keys. + +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._keys import is_within, relativize -from zarr_storage._types import Key, Prefix +from zarr_storage._types import Key, Missing, Prefix, Rejected if TYPE_CHECKING: from collections.abc import Iterable, Iterator - from zarr_storage._types import ListItem + from zarr_storage._types import Generation, ListItem + +__all__ = ["IfMatch", "always", "children", "if_absent", "strictly_within"] + + +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 -__all__ = ["children", "strictly_within"] + 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: diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index 08f08dee2f..5759c7d0ba 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -25,21 +25,25 @@ UnsupportedOperationError, ) from zarr_storage._types import ( - DeleteResult, + Copied, + Deleted, + Found, + FoundRanges, Generation, Key, + Missing, ObjectMetadata, Prefix, - PutResult, - RangesResult, - ReadResult, + Unchanged, + Written, ) +from zarr_storage.backends._common import IfMatch, always, if_absent if TYPE_CHECKING: from collections.abc import AsyncIterator, Callable, Generator, Iterator, Sequence from io import BufferedReader - from zarr_storage._types import ByteRange, ListItem + from zarr_storage._types import ByteRange, ListItem, Rejected __all__ = ["RESERVED_SUFFIX", "LocalBackend", "segment_problem"] @@ -66,6 +70,7 @@ _WINDOWS_FORBIDDEN_CHARACTERS = frozenset('<>:"\\|?*') | frozenset(chr(i) for i in range(32)) P = ParamSpec("P") +R = TypeVar("R") T = TypeVar("T") @@ -171,6 +176,13 @@ def _open_key(file: Path) -> BufferedReader | None: 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): @@ -242,10 +254,9 @@ def _replace_if( path: str, temp: Path, staged: Generation, - if_match: Generation | None, - if_none_match: bool, -) -> PutResult: - """Rename `temp` to `file` if the preconditions hold. The caller holds the directory's lock. + 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 @@ -254,9 +265,9 @@ def _replace_if( 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) - current = None if st is None else _generation(st) - if (if_none_match and current is not None) or (if_match is not None and if_match != current): - return PutResult(current, applied=False) + 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: @@ -274,7 +285,7 @@ def _replace_if( if e.errno in _TRANSIENT_ERRNOS: raise _Retry from e raise - return PutResult(staged) + return Written(staged) def _is_real_directory(path: Path) -> bool: @@ -453,23 +464,32 @@ def _directory(self, directory: str) -> Path: # --- Readable - def get(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: + 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 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()) - start, end = resolve(byte_range, st.st_size) - f.seek(start) - data = f.read(end - start) - return ReadResult(memoryview(data), _generation(st)) + if _generation(st) == generation: + return Unchanged(generation, time.time()) + return _read(f, st, byte_range) - def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + 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 None + return Missing(time.time()) parts: list[memoryview] = [] with f: st = os.fstat(f.fileno()) @@ -477,13 +497,15 @@ def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | N start, end = resolve(byte_range, st.st_size) f.seek(start) parts.append(memoryview(f.read(end - start))) - return RangesResult(tuple(parts), _generation(st)) + return FoundRanges(tuple(parts), _generation(st), time.time()) - def get_into(self, path: str, out: memoryview, byte_range: ByteRange | None) -> int | None: + def get_into( + self, path: str, out: memoryview, byte_range: ByteRange | None + ) -> Copied | Missing: with _key_errors(path): f = _open_key(self._file(path)) if f is None: - return None + return Missing(time.time()) with f: st = os.fstat(f.fileno()) start, end = resolve(byte_range, st.st_size) @@ -492,30 +514,40 @@ def get_into(self, path: str, out: memoryview, byte_range: ByteRange | None) -> raise ValueError(f"The output buffer holds {len(out)} bytes; the value has {n}.") f.seek(start) _read_exact_into(f, out[:n]) - return n + return Copied(n, _generation(st), time.time()) - def head(self, path: str) -> ObjectMetadata | None: + def head(self, path: str) -> ObjectMetadata | Missing: with _key_errors(path): st = _stat_key(self._file(path)) if st is None: - return None + return Missing(time.time()) return ObjectMetadata(st.st_size, _generation(st), st.st_mtime) # --- Writable - def put( - self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool - ) -> PutResult: + 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) - if if_match is not None or if_none_match: - self._require_exact_times() 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, if_match, if_none_match) + return self._commit(file, path, temp, staged, check) except _Retry as retry: last = retry time.sleep(min(1e-4 * 2**attempt, 1e-2)) @@ -595,10 +627,9 @@ def _commit( path: str, temp: Path, staged: Generation, - if_match: Generation | None, - if_none_match: bool, - ) -> PutResult: - """Rename `temp` to `file` if the preconditions hold, under the lock of `file`'s directory. + 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. """ @@ -617,26 +648,34 @@ def _commit( raise _Retry from e raise with _directory_lock(file.parent): - return _replace_if(file, path, temp, staged, if_match, if_none_match) + return _replace_if(file, path, temp, staged, check) + + def delete(self, path: str) -> Deleted | Missing: + return self._delete(path, always) - def delete(self, path: str, *, if_match: Generation | None) -> DeleteResult: + 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) - if if_match is not None: - self._require_exact_times() with _key_errors(path): try: with _directory_lock(file.parent): st = _stat_key(file) if st is None: - return DeleteResult(None, applied=False) + return Missing(time.time()) current = _generation(st) - if if_match is not None and if_match != current: - return DeleteResult(current, applied=False) + 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 DeleteResult(None, applied=False) - return DeleteResult(current, applied=True) + return Missing(time.time()) + return Deleted(current) def delete_dir(self, directory: str) -> None: target = self._directory(directory) @@ -679,29 +718,45 @@ async def _run(self, fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T loop = asyncio.get_running_loop() return await loop.run_in_executor(self._pool(), partial(fn, *args, **kwargs)) - async def get_async(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: + async def get_async(self, path: str, byte_range: ByteRange | None) -> Found | Missing: return await self._run(self.get, path, byte_range) - async def get_ranges_async(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + async def get_if_changed_async( + self, path: str, generation: Generation, byte_range: ByteRange | None + ) -> Found | Missing | Unchanged: + return await self._run(self.get_if_changed, path, generation, byte_range) + + async def get_ranges_async( + self, path: str, ranges: Sequence[ByteRange] + ) -> FoundRanges | Missing: return await self._run(self.get_ranges, path, ranges) - async def head_async(self, path: str) -> ObjectMetadata | None: + async def head_async(self, path: str) -> ObjectMetadata | Missing: return await self._run(self.head, path) async def get_into_async( self, path: str, out: memoryview, byte_range: ByteRange | None - ) -> int | None: + ) -> Copied | Missing: return await self._run(self.get_into, path, out, byte_range) - async def put_async( - self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool - ) -> PutResult: - return await self._run( - self.put, path, value, if_match=if_match, if_none_match=if_none_match - ) + async def put_async(self, path: str, value: memoryview) -> Written: + return await self._run(self.put, path, value) + + async def put_if_absent_async(self, path: str, value: memoryview) -> Written | Rejected: + return await self._run(self.put_if_absent, path, value) + + async def put_if_match_async( + self, path: str, value: memoryview, generation: Generation + ) -> Written | Rejected | Missing: + return await self._run(self.put_if_match, path, value, generation) + + async def delete_async(self, path: str) -> Deleted | Missing: + return await self._run(self.delete, path) - async def delete_async(self, path: str, *, if_match: Generation | None) -> DeleteResult: - return await self._run(self.delete, path, if_match=if_match) + async def delete_if_match_async( + self, path: str, generation: Generation + ) -> Deleted | Rejected | Missing: + return await self._run(self.delete_if_match, path, generation) async def delete_dir_async(self, directory: str) -> None: await self._run(self.delete_dir, directory) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_memory.py b/packages/zarr-storage/src/zarr_storage/backends/_memory.py index e474cdd365..64b6cf281d 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_memory.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_memory.py @@ -5,26 +5,31 @@ import threading import time from dataclasses import dataclass -from typing import TYPE_CHECKING, TypedDict +from typing import TYPE_CHECKING, TypedDict, TypeVar from zarr_storage._byte_range import resolve from zarr_storage._types import ( - DeleteResult, + Copied, + Deleted, + Found, + FoundRanges, Generation, + Missing, ObjectMetadata, - PutResult, - RangesResult, - ReadResult, + Unchanged, + Written, ) -from zarr_storage.backends._common import children, strictly_within +from zarr_storage.backends._common import IfMatch, always, children, if_absent, strictly_within if TYPE_CHECKING: - from collections.abc import AsyncIterator, Iterator, Sequence + from collections.abc import AsyncIterator, Callable, Iterator, Sequence - from zarr_storage._types import ByteRange, ListItem + from zarr_storage._types import ByteRange, ListItem, Rejected __all__ = ["MemoryBackend"] +R = TypeVar("R") + @dataclass(frozen=True, slots=True) class _Value: @@ -84,67 +89,94 @@ def close(self) -> None: # --- Readable - def get(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: + def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: value = self._values.get(path) if value is None: - return None + return Missing(time.time()) start, end = resolve(byte_range, len(value.data)) - return ReadResult(memoryview(value.data)[start:end], Generation(value.generation)) + 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]) -> RangesResult | None: + def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> FoundRanges | Missing: value = self._values.get(path) if value is None: - return None + return Missing(time.time()) view = memoryview(value.data) - size = len(value.data) - parts = tuple(view[slice(*resolve(r, size))] for r in ranges) - return RangesResult(parts, Generation(value.generation)) + 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 | None: + def head(self, path: str) -> ObjectMetadata | Missing: value = self._values.get(path) if value is None: - return None + return Missing(time.time()) return ObjectMetadata(len(value.data), Generation(value.generation), value.last_modified) - def get_into(self, path: str, out: memoryview, byte_range: ByteRange | None) -> int | None: + def get_into( + self, path: str, out: memoryview, byte_range: ByteRange | None + ) -> Copied | Missing: value = self._values.get(path) if value is None: - return None + return Missing(time.time()) start, end = resolve(byte_range, len(value.data)) n = end - start if n > len(out): raise ValueError(f"The output buffer holds {len(out)} bytes; the value has {n}.") out[:n] = memoryview(value.data)[start:end] - return n + return Copied(n, Generation(value.generation), time.time()) # --- Writable - def put( - self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool - ) -> PutResult: + 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) - current_generation = None if current is None else Generation(current.generation) - if if_none_match and current is not None: - return PutResult(current_generation, applied=False) - if if_match is not None and if_match != current_generation: - return PutResult(current_generation, applied=False) + 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 PutResult(Generation(generation)) + 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 delete(self, path: str, *, if_match: Generation | None) -> DeleteResult: + 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 DeleteResult(None, applied=False) - current_generation = Generation(current.generation) - if if_match is not None and if_match != current_generation: - return DeleteResult(current_generation, applied=False) + return Missing(time.time()) + generation = Generation(current.generation) + refusal = check(generation) + if refusal is not None: + return refusal del self._values[path] - return DeleteResult(current_generation, applied=True) + 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: @@ -165,27 +197,45 @@ def list_dir(self, directory: str) -> Iterator[ListItem]: # --- async twins: memory never blocks, so they run inline - async def get_async(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: + async def get_async(self, path: str, byte_range: ByteRange | None) -> Found | Missing: return self.get(path, byte_range) - async def get_ranges_async(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + 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 | None: + async def head_async(self, path: str) -> ObjectMetadata | Missing: return self.head(path) async def get_into_async( self, path: str, out: memoryview, byte_range: ByteRange | None - ) -> int | None: + ) -> Copied | Missing: return self.get_into(path, out, byte_range) - async def put_async( - self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool - ) -> PutResult: - return self.put(path, value, if_match=if_match, if_none_match=if_none_match) + 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_async(self, path: str, *, if_match: Generation | None) -> DeleteResult: - return self.delete(path, if_match=if_match) + 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) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py index ee038de086..54d8fab4b3 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py @@ -11,42 +11,57 @@ import contextlib import errno import os +import time from pathlib import Path -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING, TypeVar, cast import obstore -from obstore.exceptions import AlreadyExistsError, GenericError, PreconditionError +from obstore.exceptions import ( + AlreadyExistsError, + GenericError, + NotModifiedError, + PreconditionError, +) from obstore.store import HTTPStore, LocalStore from zarr_storage._byte_range import resolve from zarr_storage._errors import InvalidKeyError, KeyConflictError, UnsupportedOperationError from zarr_storage._keys import check_key, relativize from zarr_storage._types import ( - DeleteResult, + Deleted, + Found, + FoundRanges, Generation, Key, + Missing, ObjectMetadata, OffsetRequest, Prefix, - PutResult, RangeRequest, - RangesResult, - ReadResult, + Rejected, SuffixRequest, + Unchanged, + Written, ) +from zarr_storage.backends._common import IfMatch, always, if_absent if TYPE_CHECKING: - from collections.abc import AsyncIterator, Iterable, Iterator, Sequence + from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Sequence - from obstore import GetOptions, ListResult, ListStream, ObjectMeta, PutMode + from obstore import GetOptions, GetResult, ListResult, ListStream, ObjectMeta, PutMode from obstore.store import ObjectStore from zarr_storage._types import ByteRange, ListItem __all__ = ["ObjectStoreBackend"] +R = TypeVar("R") + _EMPTY = memoryview(b"") +_PUT_ATTEMPTS = 16 +"""How many times a write starts over when the store refused it for a state that then went away.""" + # ---------------------------------------------------------------------------- generations @@ -72,21 +87,12 @@ def _version_of(generation: object) -> tuple[str | None, str | None] | None: return None -class _NeverMatches: - """The precondition names a generation this backend did not mint, so no stored value has it.""" - - -_NEVER_MATCHES = _NeverMatches() - - -def _put_mode(if_match: Generation | None, if_none_match: bool) -> PutMode | _NeverMatches | None: - if if_none_match: - return "create" - if if_match is None: - return None - version = _version_of(if_match) +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 _NEVER_MATCHES + return None e_tag, object_version = version if e_tag is None and object_version is None: raise UnsupportedOperationError( @@ -96,6 +102,23 @@ def _put_mode(if_match: Generation | None, if_none_match: bool) -> PutMode | _Ne 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 @@ -123,19 +146,19 @@ def _is_empty_request(byte_range: ByteRange | None) -> bool: def _empty_read_or_raise( - meta: ObjectMetadata | None, byte_range: ByteRange | None, error: BaseException | None -) -> ReadResult | None: + 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 meta is None: - return None + if isinstance(meta, Missing): + return meta start, end = resolve(byte_range, meta.size) if start == end: - return ReadResult(_EMPTY, meta.generation) + return Found(_EMPTY, meta.generation, time.time()) if error is not None: raise error raise AssertionError("A non-empty range was treated as empty.") @@ -218,10 +241,10 @@ def _ancestors(path: str) -> list[str]: class ObjectStoreBackend: """Keys stored in an obstore store. - Generations are the store's ETag and version. Conditional writes need a store that supports them - (S3, GCS, Azure and obstore's `MemoryStore` do; obstore's `LocalStore` supports only - `if_none_match`); otherwise they raise `UnsupportedOperationError`. Conditional deletes are not - supported. + 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 @@ -352,58 +375,85 @@ async def _conflicts_async(self, path: str) -> bool: # --- Readable - def head(self, path: str) -> ObjectMetadata | None: + def head(self, path: str) -> ObjectMetadata | Missing: try: return _metadata(obstore.head(self._store, path)) except FileNotFoundError: - return None + return Missing(time.time()) except GenericError: if self._under_a_key(path): - return None + return Missing(time.time()) raise - async def head_async(self, path: str) -> ObjectMetadata | None: + async def head_async(self, path: str) -> ObjectMetadata | Missing: try: return _metadata(await obstore.head_async(self._store, path)) except FileNotFoundError: - return None + return Missing(time.time()) except GenericError: if await self._under_a_key_async(path): - return None + return Missing(time.time()) raise - def get(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: + 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_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=_get_options(byte_range)) + result = obstore.get(self._store, path, options={**options, **_get_options(byte_range)}) except FileNotFoundError: - return None + return Missing(time.time()) except GenericError as e: return _empty_read_or_raise(self.head(path), byte_range, e) - meta = result.meta - return ReadResult(memoryview(result.bytes()), _generation(meta["e_tag"], meta["version"])) + return _found(result, memoryview(result.bytes())) - async def get_async(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: + 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=_get_options(byte_range)) + result = await obstore.get_async( + self._store, path, options={**options, **_get_options(byte_range)} + ) except FileNotFoundError: - return None + return Missing(time.time()) except GenericError as e: return _empty_read_or_raise(await self.head_async(path), byte_range, e) - meta = result.meta - data = await result.bytes_async() - return ReadResult(memoryview(data), _generation(meta["e_tag"], meta["version"])) + return _found(result, memoryview(await result.bytes_async())) - def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + 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 None + 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) @@ -417,7 +467,7 @@ def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | N 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 RangesResult((memoryview(first.bytes()), *rest), generation) + 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: @@ -426,25 +476,29 @@ def _read_pinned(self, path: str, pinned: GetOptions, start: int, end: int) -> m _check_pinned(result.meta, pinned) return memoryview(result.bytes()) - def _read_whole_and_slice(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + def _read_whole_and_slice( + self, path: str, ranges: Sequence[ByteRange] + ) -> FoundRanges | Missing: try: result = obstore.get(self._store, path) except FileNotFoundError: - return None + return Missing(time.time()) except GenericError: if self._under_a_key(path): - return None + return Missing(time.time()) raise generation = _generation(result.meta["e_tag"], result.meta["version"]) - return RangesResult(_slices(memoryview(result.bytes()), ranges), generation) + return FoundRanges(_slices(memoryview(result.bytes()), ranges), generation, time.time()) - async def get_ranges_async(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + 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 None + return Missing(time.time()) except GenericError: return await self._read_whole_and_slice_async(path, ranges) meta = first.meta @@ -461,107 +515,147 @@ async def get_ranges_async(self, path: str, ranges: Sequence[ByteRange]) -> Rang ) except (PreconditionError, FileNotFoundError): return await self._read_whole_and_slice_async(path, ranges) - return RangesResult((memoryview(await first.bytes_async()), *rest), generation) + return FoundRanges((memoryview(await first.bytes_async()), *rest), generation, time.time()) async def _read_whole_and_slice_async( self, path: str, ranges: Sequence[ByteRange] - ) -> RangesResult | None: + ) -> FoundRanges | Missing: try: result = await obstore.get_async(self._store, path) except FileNotFoundError: - return None + return Missing(time.time()) except GenericError: if await self._under_a_key_async(path): - return None + return Missing(time.time()) raise generation = _generation(result.meta["e_tag"], result.meta["version"]) - return RangesResult(_slices(memoryview(await result.bytes_async()), ranges), generation) + data = memoryview(await result.bytes_async()) + return FoundRanges(_slices(data, ranges), generation, time.time()) # --- Writable - def put( - self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool - ) -> PutResult: - mode = _put_mode(if_match, if_none_match) - if isinstance(mode, _NeverMatches): - return PutResult(_generation_or_none(self.head(path)), applied=False) - 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 current is None and self._reclaim_empty_directory(path): - return self.put(path, value, if_match=if_match, if_none_match=if_none_match) - if current is None and self._conflicts(path): - raise _conflict(path, self._store) from None - return PutResult(_generation_or_none(current), applied=False) - 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): - return self.put(path, value, if_match=if_match, if_none_match=if_none_match) - if self._conflicts(path) or self._is_directory(path): - raise _conflict(path, self._store) from e - raise - return PutResult(_generation(result["e_tag"], result["version"])) - - async def put_async( - self, path: str, value: memoryview, *, if_match: Generation | None, if_none_match: bool - ) -> PutResult: - mode = _put_mode(if_match, if_none_match) - if isinstance(mode, _NeverMatches): - return PutResult(_generation_or_none(await self.head_async(path)), applied=False) - try: - result = await obstore.put_async(self._store, path, bytes(value), mode=mode) - except (AlreadyExistsError, PreconditionError): - current = await self.head_async(path) - if current is None and await asyncio.to_thread(self._reclaim_empty_directory, path): - return await self.put_async( - path, value, if_match=if_match, if_none_match=if_none_match - ) - if current is None and await self._conflicts_async(path): - raise _conflict(path, self._store) from None - return PutResult(_generation_or_none(current), applied=False) - 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): - return await self.put_async( - path, value, if_match=if_match, if_none_match=if_none_match - ) - if await self._conflicts_async(path) or await asyncio.to_thread( - self._is_directory, path - ): - raise _conflict(path, self._store) from e - raise - return PutResult(_generation(result["e_tag"], result["version"])) + 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, *, if_match: Generation | None) -> DeleteResult: - _refuse_conditional_delete(if_match) + def delete(self, path: str) -> Deleted | Missing: meta = self.head(path) - if meta is None: - return DeleteResult(None, applied=False) + if isinstance(meta, Missing): + return meta try: obstore.delete(self._store, path) except FileNotFoundError: - return DeleteResult(None, applied=False) - return DeleteResult(meta.generation, applied=True) + return Missing(time.time()) + return Deleted(meta.generation) - async def delete_async(self, path: str, *, if_match: Generation | None) -> DeleteResult: - _refuse_conditional_delete(if_match) + async def delete_async(self, path: str) -> Deleted | Missing: meta = await self.head_async(path) - if meta is None: - return DeleteResult(None, applied=False) + if isinstance(meta, Missing): + return meta try: await obstore.delete_async(self._store, path) except FileNotFoundError: - return DeleteResult(None, applied=False) - return DeleteResult(meta.generation, applied=True) + return Missing(time.time()) + return Deleted(meta.generation) def delete_dir(self, directory: str) -> None: paths = list(self._paths(directory)) @@ -676,13 +770,17 @@ def _remove_empty_directories(target: Path) -> bool: return True -def _generation_or_none(meta: ObjectMetadata | None) -> Generation | None: - return None if meta is None else meta.generation +def _unless_unchanged( + result: Found | Missing, generation: Generation +) -> Found | Missing | Unchanged: + """`Unchanged` for a value read whole although it has `generation`. - -def _refuse_conditional_delete(if_match: Generation | None) -> None: - if if_match is not None: - raise UnsupportedOperationError("Object stores do not support conditional deletes.") + That happens when the store can't skip the read (no ETag to send, or it ignores + `If-None-Match`); the bytes are discarded so the outcome doesn't depend on the store. + """ + if isinstance(result, Found) and result.generation == generation: + return Unchanged(generation, result.read_at) + return result def _conflict(path: str, store: ObjectStore) -> KeyConflictError: diff --git a/packages/zarr-storage/src/zarr_storage/testing/__init__.py b/packages/zarr-storage/src/zarr_storage/testing/__init__.py index 50e08e7c8a..1e85817714 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/__init__.py +++ b/packages/zarr-storage/src/zarr_storage/testing/__init__.py @@ -4,7 +4,7 @@ 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`, `NoConditionalDeleteSuite`, +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. """ @@ -16,7 +16,6 @@ ConditionalRaceSuite, KeyAndDirectorySuite, KeyDirectoryConflictSuite, - NoConditionalDeleteSuite, NoConditionalPutSuite, PickleSuite, StoreSuite, @@ -31,7 +30,6 @@ "FullBackend", "KeyAndDirectorySuite", "KeyDirectoryConflictSuite", - "NoConditionalDeleteSuite", "NoConditionalPutSuite", "PickleSuite", "StoreAPI", diff --git a/packages/zarr-storage/src/zarr_storage/testing/_api.py b/packages/zarr-storage/src/zarr_storage/testing/_api.py index d3e7c4e305..c34d26ec94 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/_api.py +++ b/packages/zarr-storage/src/zarr_storage/testing/_api.py @@ -7,7 +7,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Protocol, Self +from typing import TYPE_CHECKING, Protocol, Self, cast from zarr_storage._protocols import ( Listable, @@ -16,6 +16,8 @@ ReadableAsync, Writable, WritableAsync, + WritableIfMatch, + WritableIfMatchAsync, ) if TYPE_CHECKING: @@ -25,25 +27,41 @@ from typing_extensions import Buffer + from zarr_storage._protocols import DeletableIfMatch, DeletableIfMatchAsync from zarr_storage._store import Store from zarr_storage._types import ( ByteRange, - DeleteResult, + Copied, + Deleted, + Found, + FoundRanges, Generation, ListItem, + Missing, ObjectMetadata, - PutResult, - RangesResult, - ReadResult, + Rejected, + Unchanged, + Written, ) -__all__ = ["AsyncAPI", "FullBackend", "StoreAPI", "unwrap"] +__all__ = ["AsyncAPI", "FullBackend", "StoreAPI", "delete_if_match", "unwrap"] class FullBackend( - Readable, Writable, Listable, ReadableAsync, WritableAsync, ListableAsync, Protocol + Readable, + Writable, + WritableIfMatch, + Listable, + ReadableAsync, + WritableAsync, + WritableIfMatchAsync, + ListableAsync, + Protocol, ): - """A backend with every sync and async capability.""" + """A backend with every capability the suite needs of all backends, sync and async. + + `DeletableIfMatch` is left out, since object stores lack it; `delete_if_match` reaches it. + """ class StoreAPI(Protocol): @@ -56,22 +74,22 @@ def read_only(self) -> bool: ... @property def closed(self) -> bool: ... - def get(self, key: str, *, byte_range: ByteRange | None = None) -> ReadResult | None: ... - def get_ranges(self, key: str, ranges: Sequence[ByteRange]) -> RangesResult | None: ... + 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 - ) -> int | None: ... - def head(self, key: str) -> ObjectMetadata | None: ... + ) -> Copied | Missing: ... + def head(self, key: str) -> ObjectMetadata | Missing: ... def exists(self, key: str) -> bool: ... - def put( - self, - key: str, - value: Buffer, - *, - if_match: Generation | None = None, - if_none_match: bool = False, - ) -> PutResult: ... - def delete(self, key: str, *, if_match: Generation | None = None) -> DeleteResult: ... + 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 list(self, directory: str = "") -> Iterator[str]: ... def list_dir(self, directory: str = "") -> Iterator[ListItem]: ... @@ -94,6 +112,15 @@ def unwrap(store: StoreAPI) -> Store[FullBackend]: 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[object]) -> object: return await anext(items) @@ -121,35 +148,47 @@ def read_only(self) -> bool: def closed(self) -> bool: return self._store.closed - def get(self, key: str, *, byte_range: ByteRange | None = None) -> ReadResult | None: + def get(self, key: str, *, byte_range: ByteRange | None = None) -> Found | Missing: return self._runner.run(self._store.get_async(key, byte_range=byte_range)) - def get_ranges(self, key: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + 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_async(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_async(key, ranges)) - def get_into(self, key: str, out: Buffer, *, byte_range: ByteRange | None = None) -> int | None: + def get_into( + self, key: str, out: Buffer, *, byte_range: ByteRange | None = None + ) -> Copied | Missing: return self._runner.run(self._store.get_into_async(key, out, byte_range=byte_range)) - def head(self, key: str) -> ObjectMetadata | None: + def head(self, key: str) -> ObjectMetadata | Missing: return self._runner.run(self._store.head_async(key)) def exists(self, key: str) -> bool: return self._runner.run(self._store.exists_async(key)) - def put( - self, - key: str, - value: Buffer, - *, - if_match: Generation | None = None, - if_none_match: bool = False, - ) -> PutResult: - return self._runner.run( - self._store.put_async(key, value, if_match=if_match, if_none_match=if_none_match) - ) + def put(self, key: str, value: Buffer) -> Written: + return self._runner.run(self._store.put_async(key, value)) + + def put_if_absent(self, key: str, value: Buffer) -> Written | Rejected: + return self._runner.run(self._store.put_if_absent_async(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_async(key, value, generation)) + + def delete(self, key: str) -> Deleted | Missing: + return self._runner.run(self._store.delete_async(key)) - def delete(self, key: str, *, if_match: Generation | None = None) -> DeleteResult: - return self._runner.run(self._store.delete_async(key, if_match=if_match)) + def delete_if_match(self, key: str, generation: Generation) -> Deleted | Rejected | Missing: + store = cast("Store[DeletableIfMatchAsync]", self._store) + return self._runner.run(store.delete_if_match_async(key, generation)) def delete_dir(self, directory: str = "") -> None: self._runner.run(self._store.delete_dir_async(directory)) diff --git a/packages/zarr-storage/src/zarr_storage/testing/_stateful.py b/packages/zarr-storage/src/zarr_storage/testing/_stateful.py index 3472907f3c..b762245455 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/_stateful.py +++ b/packages/zarr-storage/src/zarr_storage/testing/_stateful.py @@ -17,7 +17,19 @@ from zarr_storage._errors import KeyConflictError from zarr_storage._keys import join -from zarr_storage._types import Generation, Key, Prefix +from zarr_storage._types import ( + Deleted, + Found, + Generation, + Key, + Missing, + ObjectMetadata, + Prefix, + Rejected, + Unchanged, + Written, +) +from zarr_storage.testing._api import delete_if_match if TYPE_CHECKING: from collections.abc import Callable @@ -91,13 +103,24 @@ def _conflicts(self, path: str) -> bool: 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(key, value, if_match=Generation(object())) + (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 _record(self, path: str, value: bytes, generation: Generation | None) -> None: - assert generation is not None + 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 _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) @@ -123,26 +146,23 @@ def put(self, data: st.DataObject, value: bytes) -> None: return raise AssertionError(f"put({path!r}) should have raised KeyConflictError") result = (self.store / root).put(key, value) - assert result.applied self._record(path, value, result.generation) @rule(data=st.data(), value=VALUES) - def put_if_none_match(self, data: st.DataObject, value: bytes) -> None: + 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(key, value, if_none_match=True) + (self.store / root).put_if_absent(key, value) except KeyConflictError: return - raise AssertionError( - f"put({path!r}, if_none_match) should have raised KeyConflictError" - ) - result = (self.store / root).put(key, value, if_none_match=True) + 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.applied, result.generation) == (False, self.generations[path]) + assert result == Rejected(self.generations[path]) else: - assert result.applied + assert isinstance(result, Written) self._record(path, value, result.generation) @precondition(lambda self: self._capabilities.conditional_put) @@ -155,12 +175,12 @@ def put_if_match(self, data: st.DataObject, value: bytes, stale: bool) -> None: return current = self.generations.get(path) expected = Generation(object()) if stale or current is None else current - result = (self.store / root).put(key, value, if_match=expected) + result = (self.store / root).put_if_match(key, value, expected) if not stale and current is not None: - assert result.applied + assert isinstance(result, Written) self._record(path, value, result.generation) else: - assert (result.applied, result.generation) == (False, current) + self._check_refused(result, path) @precondition( lambda self: ( @@ -177,8 +197,8 @@ def put_if_match_retired(self, data: st.DataObject, value: bytes) -> None: self._expect_conflict(root, key, value) return retired = data.draw(st.sampled_from(self.retired), label="retired generation") - result = (self.store / root).put(key, value, if_match=retired) - assert (result.applied, result.generation) == (False, self.generations.get(join(root, key))) + result = (self.store / root).put_if_match(key, value, retired) + self._check_refused(result, join(root, key)) @rule(data=st.data()) def delete(self, data: st.DataObject) -> None: @@ -186,10 +206,10 @@ def delete(self, data: st.DataObject) -> None: path = join(root, key) result = (self.store / root).delete(key) if path in self.values: - assert (result.applied, result.generation) == (True, self.generations[path]) + assert result == Deleted(self.generations[path]) self._forget(path) else: - assert (result.applied, result.generation) == (False, None) + assert isinstance(result, Missing) @precondition(lambda self: self._capabilities.conditional_delete) @rule(data=st.data(), stale=st.booleans()) @@ -198,12 +218,12 @@ def delete_if_match(self, data: st.DataObject, stale: bool) -> None: path = join(root, key) current = self.generations.get(path) expected = Generation(object()) if stale or current is None else current - result = (self.store / root).delete(key, if_match=expected) + result = delete_if_match(self.store / root, key, expected) if not stale and current is not None: - assert (result.applied, result.generation) == (True, current) + assert result == Deleted(current) self._forget(path) else: - assert (result.applied, result.generation) == (False, current) + self._check_refused(result, path) @precondition( lambda self: ( @@ -216,8 +236,8 @@ def delete_if_match(self, data: st.DataObject, stale: bool) -> None: 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 = (self.store / root).delete(key, if_match=retired) - assert (result.applied, result.generation) == (False, self.generations.get(join(root, key))) + 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: @@ -259,12 +279,16 @@ def reads_match_the_model(self) -> None: return assert set(self.store.list()) == set(self.values) for path, value in self.values.items(): + generation = self.generations[path] result = self.store.get(path) - assert result is not None - assert (bytes(result.value), result.generation) == (value, self.generations[path]) + assert isinstance(result, Found) + assert (bytes(result.value), result.generation) == (value, generation) meta = self.store.head(path) - assert meta is not None - assert (meta.size, meta.generation) == (len(value), self.generations[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"): diff --git a/packages/zarr-storage/src/zarr_storage/testing/_suite.py b/packages/zarr-storage/src/zarr_storage/testing/_suite.py index 5b15cc544d..3dc4d60c3b 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/_suite.py +++ b/packages/zarr-storage/src/zarr_storage/testing/_suite.py @@ -33,14 +33,22 @@ UnsupportedOperationError, ) from zarr_storage._types import ( + Copied, + Deleted, + Found, Generation, Key, + Missing, + ObjectMetadata, OffsetRequest, Prefix, RangeRequest, + Rejected, SuffixRequest, + Unchanged, + Written, ) -from zarr_storage.testing._api import AsyncAPI, FullBackend, StoreAPI, unwrap +from zarr_storage.testing._api import AsyncAPI, FullBackend, StoreAPI, delete_if_match, unwrap from zarr_storage.testing._stateful import Capabilities, StoreMachine if TYPE_CHECKING: @@ -58,7 +66,6 @@ "ConditionalRaceSuite", "KeyAndDirectorySuite", "KeyDirectoryConflictSuite", - "NoConditionalDeleteSuite", "NoConditionalPutSuite", "PickleSuite", "StoreSuite", @@ -101,40 +108,64 @@ @dataclass(frozen=True) class PutCase: present: bool - precondition: Literal["none", "if_none_match", "if_match_current", "if_match_stale"] - applied: bool - generation: Literal["new", "current", "none"] + operation: Literal["put", "put_if_absent", "put_if_match_current", "put_if_match_stale"] + outcome: type[Written | Rejected | Missing] -UNCONDITIONAL_PUT_CASES = [ - PutCase(present=False, precondition="none", applied=True, generation="new"), - PutCase(present=True, precondition="none", applied=True, generation="new"), - PutCase(present=False, precondition="if_none_match", applied=True, generation="new"), - PutCase(present=True, precondition="if_none_match", applied=False, generation="current"), +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), ] -IF_MATCH_PUT_CASES = [ - PutCase(present=True, precondition="if_match_current", applied=True, generation="new"), - PutCase(present=True, precondition="if_match_stale", applied=False, generation="current"), - PutCase(present=False, precondition="if_match_stale", applied=False, generation="none"), +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 - precondition: Literal["none", "if_match_current", "if_match_stale"] - applied: bool - generation: Literal["current", "none"] + operation: Literal["delete", "delete_if_match_current", "delete_if_match_stale"] + outcome: type[Deleted | Rejected | Missing] -UNCONDITIONAL_DELETE_CASES = [ - DeleteCase(present=False, precondition="none", applied=False, generation="none"), - DeleteCase(present=True, precondition="none", applied=True, generation="current"), +DELETE_CASES = [ + DeleteCase(present=False, operation="delete", outcome=Missing), + DeleteCase(present=True, operation="delete", outcome=Deleted), ] -IF_MATCH_DELETE_CASES = [ - DeleteCase(present=True, precondition="if_match_current", applied=True, generation="current"), - DeleteCase(present=True, precondition="if_match_stale", applied=False, generation="current"), - DeleteCase(present=False, precondition="if_match_stale", applied=False, generation="none"), +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), ] TREE = [ @@ -287,20 +318,28 @@ def _missing_head(store: StoreAPI) -> object: return store.head("a") -def _missing_exists(store: StoreAPI) -> object: - return store.exists("a") +def _missing_get_if_changed(store: StoreAPI) -> object: + return store.get_if_changed("missing", _stale()) -MISSING_READS: list[tuple[Callable[[StoreAPI], object], object]] = [ - (_missing_get, None), - (_missing_get_directory, None), - (_missing_get_range, None), - (_missing_get_ranges, None), - (_missing_get_into, None), - (_missing_head, None), - (_missing_exists, False), +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_head, +] +MISSING_READ_IDS = [ + "get", + "get-directory", + "get-range", + "get_if_changed", + "get_ranges", + "get_into", + "head", ] -MISSING_READ_IDS = ["get", "get-directory", "get-range", "get_ranges", "get_into", "head", "exists"] def _put(store: StoreAPI) -> object: @@ -374,57 +413,60 @@ def _write_repeatedly( fill = 0 while not stop.is_set(): fill = (fill + 1) % 256 - generation = store.put("k", bytes([fill]) * 1000).generation - assert generation is not None - written[generation] = fill + 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(store.put(key, VALUE, if_none_match=True).applied) + 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.precondition: - case "none": + match case.operation: + case "put": result = store.put("k", b"new") - case "if_none_match": - result = store.put("k", b"new", if_none_match=True) - case "if_match_current": + 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("k", b"new", if_match=current) - case "if_match_stale": - result = store.put("k", b"new", if_match=_stale()) - assert result.applied is case.applied - match case.generation: - case "new": - assert result.generation is not None - assert result.generation != current - case "current": - assert result.generation == current - case "none": - assert result.generation is 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") - expected = b"new" if case.applied else (VALUE if case.present else None) - assert (None if stored is None else bytes(stored.value)) == expected + 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.precondition: - case "none": + match case.operation: + case "delete": result = store.delete("k") - case "if_match_current": + case "delete_if_match_current": assert current is not None - result = store.delete("k", if_match=current) - case "if_match_stale": - result = store.delete("k", if_match=_stale()) - assert result.applied is case.applied - assert result.generation == (current if case.generation == "current" else None) - assert store.exists("k") is (case.present and not case.applied) + 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: @@ -499,7 +541,7 @@ def test_state_machine( def test_valid_key_round_trips(self, store: StoreAPI, key: str) -> None: store.put(key, VALUE) result = store.get(key) - assert result is not None + assert isinstance(result, Found) assert bytes(result.value) == VALUE assert key in set(store.list()) @@ -526,12 +568,12 @@ def test_invalid_directory_raises( ) def test_put_then_get(self, store: StoreAPI, value: Buffer, expected: bytes) -> None: written = store.put("k", value) - assert written.applied result = store.get("k") - assert result is not None + 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 meta is not None + 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") @@ -541,15 +583,30 @@ def test_put_copies_the_value(self, store: StoreAPI) -> None: store.put("k", value) value[0:1] = b"X" result = store.get("k") - assert result is not None + assert isinstance(result, Found) assert bytes(result.value) == VALUE - @pytest.mark.parametrize(("read", "expected"), MISSING_READS, ids=MISSING_READ_IDS) + @pytest.mark.parametrize("read", MISSING_READS, ids=MISSING_READ_IDS) def test_reads_of_missing_key( - self, store: StoreAPI, read: Callable[[StoreAPI], object], expected: object + self, store: StoreAPI, read: Callable[[StoreAPI], object] ) -> None: store.put("a/k", VALUE) - assert read(store) == expected + 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 @@ -559,15 +616,16 @@ def test_byte_range( ) -> None: store.put("k", VALUE) result = store.get("k", byte_range=byte_range) - assert result is not None + assert isinstance(result, Found) assert bytes(result.value) == expected out = bytearray(len(VALUE) + 1) - n = store.get_into("k", out, byte_range=byte_range) - assert n == len(expected) - assert bytes(out[:n]) == expected + 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 ranges is not None + assert not isinstance(ranges, Missing) assert [bytes(v) for v in ranges.values] == [expected, b"9"] assert ranges.generation == result.generation @@ -598,9 +656,7 @@ def test_get_ranges_reads_one_generation(self, tmp_path: Path, api: str) -> None generation the result reports.""" store = self.make_store(tmp_path) written: dict[Generation, int] = {} - put = store.put("k", bytes(1000)) - assert put.generation is not None - written[put.generation] = 0 + 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]] = [] @@ -610,7 +666,7 @@ def test_get_ranges_reads_one_generation(self, tmp_path: Path, api: str) -> None reader: StoreAPI = store if api == "sync" else AsyncAPI(store, runner) for _ in range(200): result = reader.get_ranges("k", [RangeRequest(0, 1), SuffixRequest(1)]) - assert result is not None + assert not isinstance(result, Missing) first, last = (bytes(v) for v in result.values) seen.append((result.generation, first, last)) finally: @@ -623,16 +679,12 @@ def test_get_ranges_reads_one_generation(self, tmp_path: Path, api: str) -> None # ------------------------------------------------------------------ writes - @pytest.mark.parametrize("case", UNCONDITIONAL_PUT_CASES, ids=repr) + @pytest.mark.parametrize("case", PUT_CASES, ids=repr) def test_put(self, store: StoreAPI, case: PutCase) -> None: _check_put(store, case) - def test_put_with_both_preconditions_raises(self, store: StoreAPI) -> None: - with pytest.raises(ValueError, match="at most one"): - store.put("k", VALUE, if_match=_stale(), if_none_match=True) - def test_concurrent_creates_apply_once(self, tmp_path: Path) -> None: - """Of many racing `if_none_match` writes to one key, exactly one applies.""" + """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) @@ -647,14 +699,13 @@ def test_concurrent_creates_apply_once(self, tmp_path: Path) -> None: thread.join() assert results.count(True) == 1 - @pytest.mark.parametrize("case", UNCONDITIONAL_DELETE_CASES, ids=repr) + @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) - result = store.delete("a") - assert (result.applied, result.generation) == (False, None) + assert isinstance(store.delete("a"), Missing) assert store.exists("a/b") @pytest.mark.parametrize(("directory", "remaining"), DELETE_DIR_CASES) @@ -705,10 +756,10 @@ def test_views_share_the_backend(self, store: StoreAPI) -> None: 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 result is not None + assert not isinstance(result, Missing) assert [bytes(v) for v in result.values] == [b"9"] meta = child.head("b/c") - assert meta is not None + assert isinstance(meta, ObjectMetadata) assert meta.size == len(VALUE) assert set((store / "lat").list()) == set() child.delete_dir() @@ -806,34 +857,32 @@ def test_generations_are_not_reused_after_deletes(self, tmp_path: Path) -> None: seen: set[Generation] = set() for i in range(200): generation = store.put(f"k{i % 3}", VALUE).generation - assert generation is not None assert generation not in seen seen.add(generation) store.delete(f"k{(i + 1) % 3}") class ConditionalPutSuite: - """For backends that support `put(if_match=...)`.""" + """For backends whose `put_if_match` works.""" - @pytest.mark.parametrize("case", IF_MATCH_PUT_CASES, ids=repr) + @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 that refuse `put(if_match=...)`.""" + """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 - assert current is not None with pytest.raises(UnsupportedOperationError): - store.put("k", b"new", if_match=current) + store.put_if_match("k", b"new", current) class ConditionalDeleteSuite: - """For backends that support `delete(if_match=...)`.""" + """For backends with `delete_if_match` (`DeletableIfMatch`).""" - @pytest.mark.parametrize("case", IF_MATCH_DELETE_CASES, ids=repr) + @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) @@ -845,7 +894,7 @@ def _race_put( results: list[str], ) -> None: barrier.wait() - if store.put("d/k", b"new", if_match=generation).applied: + if isinstance(store.put_if_match("d/k", b"new", generation), Written): results.append("put") @@ -856,7 +905,7 @@ def _race_delete( results: list[str], ) -> None: barrier.wait() - if store.delete("d/k", if_match=generation).applied: + if isinstance(delete_if_match(store, "d/k", generation), Deleted): results.append("delete") @@ -870,7 +919,6 @@ 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 - assert generation is not None barrier = threading.Barrier(4) results: list[str] = [] threads = [ @@ -884,16 +932,6 @@ def test_conditional_put_and_delete_apply_once(self, tmp_path: Path) -> None: assert len(results) == 1 -class NoConditionalDeleteSuite: - """For backends that refuse `delete(if_match=...)`.""" - - def test_delete_if_match_raises(self, store: StoreAPI) -> None: - current = store.put("k", VALUE).generation - assert current is not None - with pytest.raises(UnsupportedOperationError): - store.delete("k", if_match=current) - - class KeyAndDirectorySuite: """For backends that hold a key `a` and a key `a/b` at once (object stores, memory).""" @@ -937,12 +975,13 @@ def test_directory_under_a_key_raises(self, store: StoreAPI) -> None: def test_reads_under_a_key_find_nothing(self, store: StoreAPI) -> None: store.put("a", VALUE) - assert store.get("a/b") is None - assert store.get_into("a/b", bytearray(len(VALUE))) is None - assert store.head("a/b") is None + 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 store.get_ranges("a/b", [SuffixRequest(1)]) is None - assert not store.delete("a/b").applied + 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() diff --git a/packages/zarr-storage/tests/test_local.py b/packages/zarr-storage/tests/test_local.py index cbc34082a6..a041d7a058 100644 --- a/packages/zarr-storage/tests/test_local.py +++ b/packages/zarr-storage/tests/test_local.py @@ -10,13 +10,16 @@ import pytest from zarr_storage import ( + Found, Generation, InvalidKeyError, Key, KeyConflictError, Prefix, + Rejected, Store, UnsupportedOperationError, + Written, ) from zarr_storage.backends import LocalBackend from zarr_storage.backends._local import RESERVED_SUFFIX, _directory_lock, segment_problem @@ -70,7 +73,7 @@ def test_delete_leaves_the_directory(tmp_path: Path) -> None: def test_failed_put_leaves_no_staged_files(tmp_path: Path) -> None: store = Store(LocalBackend(tmp_path)) store.put("k", b"x") - assert not store.put("k", b"y", if_none_match=True).applied + assert isinstance(store.put_if_absent("k", b"y"), Rejected) assert list((tmp_path / f"staging{RESERVED_SUFFIX}").iterdir()) == [] @@ -82,7 +85,7 @@ def test_delete_dir_of_the_root_keeps_backend_files(tmp_path: Path) -> None: f"lock{RESERVED_SUFFIX}", f"staging{RESERVED_SUFFIX}", } - assert store.put("k", b"y", if_none_match=True).applied + assert isinstance(store.put_if_absent("k", b"y"), Written) def test_put_recreates_a_removed_root(tmp_path: Path) -> None: @@ -90,7 +93,7 @@ def test_put_recreates_a_removed_root(tmp_path: Path) -> None: outer = Store(LocalBackend(tmp_path)) inner = Store(LocalBackend(tmp_path / "sub")) outer.delete_dir("sub") - assert inner.put("k", b"x").applied + inner.put("k", b"x") assert outer.exists("sub/k") @@ -151,14 +154,14 @@ def _create( store: Store[LocalBackend], key: str, barrier: threading.Barrier, results: list[bool] ) -> None: barrier.wait() - results.append(store.put(key, b"x", if_none_match=True).applied) + 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 `if_none_match` writes to one key, exactly one applies, even through + """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(tmp_path / "sub")) if overlapping_roots else outer / "sub" @@ -179,7 +182,7 @@ def test_concurrent_creates_through_overlapping_roots( def _create_in_process(root: str, key: str, start: threading.Event) -> bool: start.wait() - return Store(LocalBackend(root)).put(key, b"x", if_none_match=True).applied + return isinstance(Store(LocalBackend(root)).put_if_absent(key, b"x"), Written) def test_concurrent_creates_apply_once_across_processes(tmp_path: Path) -> None: @@ -265,9 +268,9 @@ def test_put_retries_a_rename_into_a_removed_directory( store = Store(LocalBackend(tmp_path)) failures = [OSError(errno.ENOENT, "removed"), OSError(errno.EINVAL, "removed")] monkeypatch.setattr(os, "replace", _FlakyReplace(failures)) - assert store.put("a/k", b"x").applied + store.put("a/k", b"x") result = store.get("a/k") - assert result is not None + assert isinstance(result, Found) assert bytes(result.value) == b"x" @@ -311,7 +314,7 @@ def test_delete_dir_waits_for_a_write_in_progress( deleter.join(5) assert outcomes == {"P/D/k": True} assert not store.exists("P/D/k") - assert store.put("P/D/k", b"y", if_none_match=True).applied + assert isinstance(store.put_if_absent("P/D/k", b"y"), Written) def test_delete_dir_leaves_a_symlinked_directory_alone(tmp_path: Path) -> None: @@ -337,7 +340,8 @@ def _put_outcome( ) -> None: barrier.wait() try: - outcomes[key] = store.put(key, b"x").applied + store.put(key, b"x") + outcomes[key] = True except KeyConflictError: outcomes[key] = False @@ -372,17 +376,17 @@ def _coarse(self: LocalBackend) -> bool: @pytest.mark.parametrize( "write", [ - lambda s: s.put("k", b"x", if_none_match=True), - lambda s: s.put("k", b"x", if_match=Generation(object())), - lambda s: s.delete("k", if_match=Generation(object())), + lambda s: s.put_if_match("k", b"x", Generation(object())), + lambda s: s.delete_if_match("k", Generation(object())), ], - ids=["put-if_none_match", "put-if_match", "delete-if_match"], + ids=["put_if_match", "delete_if_match"], ) -def test_conditional_writes_on_a_filesystem_that_rounds_times_raise( +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 store.put("k", b"x").applied + assert isinstance(store.put_if_absent("k", b"x"), Written) diff --git a/packages/zarr-storage/tests/test_obstore.py b/packages/zarr-storage/tests/test_obstore.py index 082df001ab..6321cbb625 100644 --- a/packages/zarr-storage/tests/test_obstore.py +++ b/packages/zarr-storage/tests/test_obstore.py @@ -8,14 +8,14 @@ from obstore.exceptions import GenericError from obstore.store import LocalStore, MemoryStore -from zarr_storage import ObjectMetadata, RangeRequest, Store +from zarr_storage import Found, ObjectMetadata, RangeRequest, Store, Unchanged from zarr_storage.backends import ObjectStoreBackend +from zarr_storage.backends import _obstore as obstore_backend from zarr_storage.backends._obstore import _empty_read_or_raise, _generation from zarr_storage.testing import ( ConditionalPutSuite, KeyAndDirectorySuite, KeyDirectoryConflictSuite, - NoConditionalDeleteSuite, NoConditionalPutSuite, PickleSuite, StoreSuite, @@ -62,7 +62,6 @@ class TestObjectStoreMemory( StoreSuite, UniqueGenerationsSuite, ConditionalPutSuite, - NoConditionalDeleteSuite, KeyAndDirectorySuite, NoBlockingCallsInAsyncRuns, ): @@ -73,7 +72,6 @@ def make_store(self, directory: Path) -> Store[ObjectStoreBackend]: class TestObjectStoreLocal( StoreSuite, NoConditionalPutSuite, - NoConditionalDeleteSuite, KeyDirectoryConflictSuite, PickleSuite, NoBlockingCallsInAsyncRuns, @@ -87,7 +85,7 @@ def make_store(self, directory: Path) -> Store[ObjectStoreBackend]: def test_refused_empty_read_is_empty() -> None: result = _empty_read_or_raise(_META, RangeRequest(10, 12), GenericError("refused")) - assert result is not None + assert isinstance(result, Found) assert (bytes(result.value), result.generation) == (b"", _META.generation) @@ -174,3 +172,23 @@ def test_errors_on_object_stores_are_not_read_as_absent( 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 (no ETag, or 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.get_if_changed_async("k", generation)) + assert result == Unchanged(generation, result.read_at) diff --git a/packages/zarr-storage/tests/test_store.py b/packages/zarr-storage/tests/test_store.py index 9ca73c3607..9bdebcd3c7 100644 --- a/packages/zarr-storage/tests/test_store.py +++ b/packages/zarr-storage/tests/test_store.py @@ -7,14 +7,17 @@ import pytest from zarr_storage import ( + Copied, + Found, + FoundRanges, Generation, + Missing, ObjectMetadata, OffsetRequest, RangeRequest, - RangesResult, - ReadResult, Store, SuffixRequest, + Unchanged, ) from zarr_storage._byte_range import resolve from zarr_storage.backends import MemoryBackend @@ -42,19 +45,24 @@ def writable(self) -> bool: def close(self) -> None: pass - def get(self, path: str, byte_range: ByteRange | None) -> ReadResult | None: + def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: data = self._values.get(path) if data is None: - return None + return Missing() start, end = resolve(byte_range, len(data)) - return ReadResult(memoryview(data)[start:end], Generation(0)) + return Found(memoryview(data)[start:end], Generation(0)) - def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> RangesResult | None: + def get_if_changed( + self, path: str, generation: Generation, byte_range: ByteRange | None + ) -> Found | Missing | Unchanged: raise NotImplementedError - def head(self, path: str) -> ObjectMetadata | None: + 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 None if data is None else ObjectMetadata(len(data), Generation(0), None) + return Missing() if data is None else ObjectMetadata(len(data), Generation(0), None) @pytest.mark.parametrize( @@ -65,9 +73,9 @@ def test_get_into_without_backend_support(byte_range: ByteRange | None, expected """A backend without `get_into` is read with `get` and copied into the buffer.""" store = Store(_ReadOnlyBackend({"a/k": b"0123"})) / "a" out = bytearray(4) - n = store.get_into("k", out, byte_range=byte_range) - assert (n, bytes(out[: n or 0])) == (len(expected), expected) - assert store.get_into("missing", out) is None + assert store.get_into("k", out, byte_range=byte_range) == Copied(len(expected), Generation(0)) + assert bytes(out[: len(expected)]) == expected + assert store.get_into("missing", out) == Missing() def test_get_into_without_backend_support_short_buffer_raises() -> None: From 1154c0b30e47eb5a59a7a09fc1a05bbb308ca14a Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 17 Nov 2026 17:19:37 +0100 Subject: [PATCH 04/31] feat(zarr-storage)!: make get_into generic in the buffer type it reads into `ReadableInto` and `ReadableIntoAsync` are now generic in the type of buffer the backend writes into, and `Store.get_into` accepts exactly that type. Host backends are `ReadableInto[Buffer]` and convert the buffer themselves; a GPU direct storage backend can be `ReadableInto` of its device buffer type, so passing it host memory (or the reverse) is a type error. The caller allocates, so the store needs no allocator. `Store.get_into` no longer falls back to `get` plus a copy for backends without `get_into`: the method is a type error on them. The obstore backend gains `get_into` (a read, then a copy), using the shared `copy_into` helper. Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-storage/DESIGN.md | 13 +++- .../zarr-storage/src/zarr_storage/_buffers.py | 41 ++++++++++ .../src/zarr_storage/_protocols.py | 26 +++++-- .../zarr-storage/src/zarr_storage/_store.py | 76 +++++++------------ .../src/zarr_storage/backends/_local.py | 16 ++-- .../src/zarr_storage/backends/_memory.py | 16 ++-- .../src/zarr_storage/backends/_obstore.py | 15 +++- .../src/zarr_storage/testing/_api.py | 8 +- packages/zarr-storage/tests/test_store.py | 52 ++++++++++--- 9 files changed, 178 insertions(+), 85 deletions(-) create mode 100644 packages/zarr-storage/src/zarr_storage/_buffers.py diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 51a2559fa4..2c2a2bd6eb 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -60,7 +60,7 @@ get them wrong on its own (the source of most bugs in the legacy API: #2190, #24 | `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` | `Copied.size` bytes written into `out`, any writable C-contiguous buffer; `ValueError` if it is too small, read-only or not contiguous | +| `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 | @@ -81,6 +81,17 @@ discover at runtime (`put_if_match` on obstore's `LocalStore`, or on a filesyste 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`. + Listing arguments are checked when the method is called; the items are produced lazily, and taking one after the store closes raises `StoreClosedError`. diff --git a/packages/zarr-storage/src/zarr_storage/_buffers.py b/packages/zarr-storage/src/zarr_storage/_buffers.py new file mode 100644 index 0000000000..3c6840ba81 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/_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._types import Copied, Found, Missing + +if TYPE_CHECKING: + from typing_extensions 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/_protocols.py b/packages/zarr-storage/src/zarr_storage/_protocols.py index 44ae50fa9d..f9855e5deb 100644 --- a/packages/zarr-storage/src/zarr_storage/_protocols.py +++ b/packages/zarr-storage/src/zarr_storage/_protocols.py @@ -15,7 +15,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Protocol +from typing import TYPE_CHECKING, Protocol, TypeVar if TYPE_CHECKING: from collections.abc import AsyncIterator, Iterator, Sequence @@ -52,6 +52,10 @@ ] +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 and whether it accepts writes at all.""" @@ -90,13 +94,19 @@ def head(self, path: str) -> ObjectMetadata | Missing: ... -class ReadableInto(Backend, Protocol): - def get_into( - self, path: str, out: memoryview, byte_range: ByteRange | None - ) -> Copied | Missing: +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. + Raises `ValueError` if `out` is shorter than the bytes to copy, or can't be written. """ ... @@ -157,9 +167,9 @@ async def get_ranges_async( async def head_async(self, path: str) -> ObjectMetadata | Missing: ... -class ReadableIntoAsync(Backend, Protocol): +class ReadableIntoAsync(Backend, Protocol[O_contra]): async def get_into_async( - self, path: str, out: memoryview, byte_range: ByteRange | None + self, path: str, out: O_contra, byte_range: ByteRange | None ) -> Copied | Missing: ... diff --git a/packages/zarr-storage/src/zarr_storage/_store.py b/packages/zarr-storage/src/zarr_storage/_store.py index b5d679c9bd..84171819ff 100644 --- a/packages/zarr-storage/src/zarr_storage/_store.py +++ b/packages/zarr-storage/src/zarr_storage/_store.py @@ -6,19 +6,20 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Final, Generic, Self, TypeVar, cast, final - -from typing_extensions import Buffer +from typing import TYPE_CHECKING, Final, Generic, Self, TypeVar, final +from zarr_storage._buffers import byte_view from zarr_storage._errors import ReadOnlyError, StoreClosedError from zarr_storage._keys import check_key, is_within, join, normalize_directory, relativize from zarr_storage._protocols import Backend -from zarr_storage._types import Copied, Found, Missing +from zarr_storage._types import Missing if TYPE_CHECKING: from collections.abc import AsyncIterator, Iterator, Sequence from types import TracebackType + from typing_extensions import Buffer + from zarr_storage._protocols import ( DeletableIfMatch, DeletableIfMatchAsync, @@ -35,7 +36,9 @@ ) from zarr_storage._types import ( ByteRange, + Copied, Deleted, + Found, FoundRanges, Generation, ListItem, @@ -48,19 +51,10 @@ __all__ = ["Store"] B_co = TypeVar("B_co", bound=Backend, covariant=True) +O = TypeVar("O") T = TypeVar("T") -def _as_bytes_view(value: Buffer, *, writable: bool) -> memoryview: - """A flat, C-contiguous byte view of a buffer.""" - 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 - - @final class Store(Generic[B_co]): """A backend seen from a root directory. @@ -237,19 +231,15 @@ def get_ranges( return self._backend.get_ranges(self._path(key), ranges) def get_into( - self: Store[Readable], key: str, out: Buffer, *, byte_range: ByteRange | None = None + 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`. + """Copy the value at `key` (or part of it) into `out`, a buffer the caller allocated. - Raises `ValueError` if `out` is shorter than the bytes to copy, read-only, or not - C-contiguous. + `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. """ - path = self._path(key) - view = _as_bytes_view(out, writable=True) - if hasattr(self._backend, "get_into"): - backend = cast("ReadableInto", self._backend) - return backend.get_into(path, view, byte_range) - return _copy_into(self._backend.get(path, byte_range), view) + return self._backend.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`.""" @@ -263,12 +253,12 @@ def exists(self: Store[Readable], key: str) -> bool: def put(self: Store[Writable], key: str, value: Buffer) -> Written: """Write `value` at `key`.""" - return self._backend.put(self._writable_path(key), _as_bytes_view(value, writable=False)) + return self._backend.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.""" return self._backend.put_if_absent( - self._writable_path(key), _as_bytes_view(value, writable=False) + self._writable_path(key), byte_view(value, writable=False) ) def put_if_match( @@ -279,7 +269,7 @@ def put_if_match( `Rejected` if the key holds another generation, `Missing` if it holds no value. """ return self._backend.put_if_match( - self._writable_path(key), _as_bytes_view(value, writable=False), generation + self._writable_path(key), byte_view(value, writable=False), generation ) def delete(self: Store[Writable], key: str) -> Deleted | Missing: @@ -340,15 +330,14 @@ async def get_ranges_async( return await self._backend.get_ranges_async(self._path(key), ranges) async def get_into_async( - self: Store[ReadableAsync], key: str, out: Buffer, *, byte_range: ByteRange | None = None + self: Store[ReadableIntoAsync[O]], + key: str, + out: O, + *, + byte_range: ByteRange | None = None, ) -> Copied | Missing: """Async `get_into`.""" - path = self._path(key) - view = _as_bytes_view(out, writable=True) - if hasattr(self._backend, "get_into_async"): - backend = cast("ReadableIntoAsync", self._backend) - return await backend.get_into_async(path, view, byte_range) - return _copy_into(await self._backend.get_async(path, byte_range), view) + return await self._backend.get_into_async(self._path(key), out, byte_range) async def head_async(self: Store[ReadableAsync], key: str) -> ObjectMetadata | Missing: """Async `head`.""" @@ -363,7 +352,7 @@ async def exists_async(self: Store[ReadableAsync], key: str) -> bool: async def put_async(self: Store[WritableAsync], key: str, value: Buffer) -> Written: """Async `put`.""" return await self._backend.put_async( - self._writable_path(key), _as_bytes_view(value, writable=False) + self._writable_path(key), byte_view(value, writable=False) ) async def put_if_absent_async( @@ -371,7 +360,7 @@ async def put_if_absent_async( ) -> Written | Rejected: """Async `put_if_absent`.""" return await self._backend.put_if_absent_async( - self._writable_path(key), _as_bytes_view(value, writable=False) + self._writable_path(key), byte_view(value, writable=False) ) async def put_if_match_async( @@ -379,7 +368,7 @@ async def put_if_match_async( ) -> Written | Rejected | Missing: """Async `put_if_match`.""" return await self._backend.put_if_match_async( - self._writable_path(key), _as_bytes_view(value, writable=False), generation + self._writable_path(key), byte_view(value, writable=False), generation ) async def delete_async(self: Store[WritableAsync], key: str) -> Deleted | Missing: @@ -413,19 +402,6 @@ async def _relativized(paths: AsyncIterator[str], root: str) -> AsyncIterator[st yield relativize(path, root) -def _copy_into(result: Found | Missing, out: memoryview) -> Copied | Missing: - """The `get_into` outcome of a `get`, copying a found value into `out`.""" - 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 - - def _restore_store( cls: type[Store[Backend]], backend: Backend, root: str, read_only: bool ) -> Store[Backend]: diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index 5759c7d0ba..c2ee719bb1 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -17,6 +17,7 @@ from pathlib import Path from typing import TYPE_CHECKING, ParamSpec, TypedDict, TypeVar +from zarr_storage._buffers import byte_view from zarr_storage._byte_range import resolve from zarr_storage._errors import ( InvalidKeyError, @@ -43,6 +44,8 @@ from collections.abc import AsyncIterator, Callable, Generator, Iterator, Sequence from io import BufferedReader + from typing_extensions import Buffer + from zarr_storage._types import ByteRange, ListItem, Rejected __all__ = ["RESERVED_SUFFIX", "LocalBackend", "segment_problem"] @@ -499,9 +502,8 @@ def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> FoundRanges | Mi parts.append(memoryview(f.read(end - start))) return FoundRanges(tuple(parts), _generation(st), time.time()) - def get_into( - self, path: str, out: memoryview, byte_range: ByteRange | None - ) -> Copied | Missing: + 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: @@ -510,10 +512,10 @@ def get_into( st = os.fstat(f.fileno()) start, end = resolve(byte_range, st.st_size) n = end - start - if n > len(out): - raise ValueError(f"The output buffer holds {len(out)} bytes; the value has {n}.") + 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, out[:n]) + _read_exact_into(f, view[:n]) return Copied(n, _generation(st), time.time()) def head(self, path: str) -> ObjectMetadata | Missing: @@ -735,7 +737,7 @@ async def head_async(self, path: str) -> ObjectMetadata | Missing: return await self._run(self.head, path) async def get_into_async( - self, path: str, out: memoryview, byte_range: ByteRange | None + self, path: str, out: Buffer, byte_range: ByteRange | None ) -> Copied | Missing: return await self._run(self.get_into, path, out, byte_range) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_memory.py b/packages/zarr-storage/src/zarr_storage/backends/_memory.py index 64b6cf281d..e7b9f7e335 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_memory.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_memory.py @@ -7,6 +7,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, TypedDict, TypeVar +from zarr_storage._buffers import byte_view from zarr_storage._byte_range import resolve from zarr_storage._types import ( Copied, @@ -24,6 +25,8 @@ if TYPE_CHECKING: from collections.abc import AsyncIterator, Callable, Iterator, Sequence + from typing_extensions import Buffer + from zarr_storage._types import ByteRange, ListItem, Rejected __all__ = ["MemoryBackend"] @@ -118,17 +121,16 @@ def head(self, path: str) -> ObjectMetadata | Missing: return Missing(time.time()) return ObjectMetadata(len(value.data), Generation(value.generation), value.last_modified) - def get_into( - self, path: str, out: memoryview, byte_range: ByteRange | None - ) -> Copied | Missing: + 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(out): - raise ValueError(f"The output buffer holds {len(out)} bytes; the value has {n}.") - out[:n] = memoryview(value.data)[start:end] + 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 @@ -214,7 +216,7 @@ async def head_async(self, path: str) -> ObjectMetadata | Missing: return self.head(path) async def get_into_async( - self, path: str, out: memoryview, byte_range: ByteRange | None + self, path: str, out: Buffer, byte_range: ByteRange | None ) -> Copied | Missing: return self.get_into(path, out, byte_range) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py index 54d8fab4b3..f8dcc61664 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py @@ -24,6 +24,7 @@ ) from obstore.store import HTTPStore, LocalStore +from zarr_storage._buffers import byte_view, copy_into from zarr_storage._byte_range import resolve from zarr_storage._errors import InvalidKeyError, KeyConflictError, UnsupportedOperationError from zarr_storage._keys import check_key, relativize @@ -50,8 +51,9 @@ from obstore import GetOptions, GetResult, ListResult, ListStream, ObjectMeta, PutMode from obstore.store import ObjectStore + from typing_extensions import Buffer - from zarr_storage._types import ByteRange, ListItem + from zarr_storage._types import ByteRange, Copied, ListItem __all__ = ["ObjectStoreBackend"] @@ -401,6 +403,17 @@ def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: 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: diff --git a/packages/zarr-storage/src/zarr_storage/testing/_api.py b/packages/zarr-storage/src/zarr_storage/testing/_api.py index c34d26ec94..ec05ed7b0a 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/_api.py +++ b/packages/zarr-storage/src/zarr_storage/testing/_api.py @@ -9,11 +9,15 @@ from typing import TYPE_CHECKING, Protocol, Self, cast +from typing_extensions import Buffer + from zarr_storage._protocols import ( Listable, ListableAsync, Readable, ReadableAsync, + ReadableInto, + ReadableIntoAsync, Writable, WritableAsync, WritableIfMatch, @@ -25,8 +29,6 @@ from collections.abc import AsyncIterator, Iterator, Sequence from types import TracebackType - from typing_extensions import Buffer - from zarr_storage._protocols import DeletableIfMatch, DeletableIfMatchAsync from zarr_storage._store import Store from zarr_storage._types import ( @@ -49,10 +51,12 @@ class FullBackend( Readable, + ReadableInto[Buffer], Writable, WritableIfMatch, Listable, ReadableAsync, + ReadableIntoAsync[Buffer], WritableAsync, WritableIfMatchAsync, ListableAsync, diff --git a/packages/zarr-storage/tests/test_store.py b/packages/zarr-storage/tests/test_store.py index 9bdebcd3c7..c8d098e1bd 100644 --- a/packages/zarr-storage/tests/test_store.py +++ b/packages/zarr-storage/tests/test_store.py @@ -65,23 +65,57 @@ def head(self, path: str) -> ObjectMetadata | Missing: 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_without_backend_support(byte_range: ByteRange | None, expected: bytes) -> None: - """A backend without `get_into` is read with `get` and copied into the buffer.""" - store = Store(_ReadOnlyBackend({"a/k": b"0123"})) / "a" - out = bytearray(4) +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 bytes(out[: len(expected)]) == expected + assert out.download(len(expected)) == expected assert store.get_into("missing", out) == Missing() -def test_get_into_without_backend_support_short_buffer_raises() -> None: - store = Store(_ReadOnlyBackend({"k": b"0123"})) - with pytest.raises(ValueError, match="holds"): - store.get_into("k", bytearray(3)) +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] def test_store_over_unwritable_backend_is_read_only() -> None: From 40c37d0b7f66c27e526c7113d0fbb2227662abd0 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 17 Nov 2026 22:21:15 +0100 Subject: [PATCH 05/31] feat(zarr-storage): add batch reads and writes Store gains get_many, get_into_many, put_many and delete_many, with async twins. A batch is a loop of the single operation run concurrently where the backend can, with no atomicity: reads are lazy and yield (request, result) pairs as they finish; writes are eager and return results in the order given. Keys are checked before any operation starts, and a write batch naming a key twice raises ValueError. After a failure a batch starts nothing new, lets running operations finish, and raises BatchError (an ExceptionGroup) whose completed and remaining fields survive except*. Store runs any backend's batches serially; the optional ReadableMany, ReadableIntoMany[O] and WritableMany capabilities (and async twins) let a backend run them its own way. LocalBackend runs them on its thread pool, and ObjectStoreBackend's async batches keep `concurrency` requests in flight. The shared runners live in zarr_storage._batch. The state machine's new batch rules found a race in ObjectStoreBackend: a read or delete under a file, concurrent with deleting that file, raised the store's raw error. A refusal carrying ENOTDIR is now read as an absent key directly, instead of by re-checking the parents. Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-storage/DESIGN.md | 49 +++- packages/zarr-storage/changes/460.feature.md | 2 +- .../zarr-storage/src/zarr_storage/__init__.py | 19 +- .../zarr-storage/src/zarr_storage/_batch.py | 111 ++++++++ .../zarr-storage/src/zarr_storage/_errors.py | 48 +++- .../src/zarr_storage/_protocols.py | 68 ++++- .../zarr-storage/src/zarr_storage/_store.py | 261 +++++++++++++++++- .../src/zarr_storage/backends/_local.py | 42 ++- .../src/zarr_storage/backends/_obstore.py | 65 ++++- .../src/zarr_storage/testing/_api.py | 40 ++- .../src/zarr_storage/testing/_stateful.py | 66 ++++- .../src/zarr_storage/testing/_suite.py | 214 +++++++++++++- packages/zarr-storage/tests/test_batch.py | 111 ++++++++ packages/zarr-storage/tests/test_store.py | 98 ++++++- 14 files changed, 1155 insertions(+), 39 deletions(-) create mode 100644 packages/zarr-storage/src/zarr_storage/_batch.py create mode 100644 packages/zarr-storage/tests/test_batch.py diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 2c2a2bd6eb..bbc31cacfd 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -69,6 +69,10 @@ get them wrong on its own (the source of most bugs in the legacy API: #2190, #24 | `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) | @@ -92,6 +96,29 @@ returning host bytes, which is what metadata documents need. Not yet: `get_range 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, 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 the single +operation one at a time; a backend that has a batch capability (`ReadableMany`, +`ReadableIntoMany[O]`, `WritableMany`, and async twins) is used instead. The rule for such +fallbacks: `Store` may fall back when only speed differs, never when behavior does. A serial batch +returns what a concurrent one 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. The batch runners in +`zarr_storage._batch` implement the windowing and failure rule once, for `Store` and backends alike. + Listing arguments are checked when the method is called; the items are produced lazily, and taking one after the store closes raises `StoreClosedError`. @@ -128,7 +155,10 @@ key (`a/b` when `a` is a key): that reads as absent. | `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`. +Every backend has `put_if_absent` and `get_if_changed`. `LocalBackend` runs batches, sync and +async, `concurrency` operations at once on its threads; `ObjectStoreBackend` keeps `concurrency` +requests of an async batch in flight and runs sync batches one request at a time; `MemoryBackend` +uses `Store`'s serial batches, which are as fast for it. `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 @@ -148,7 +178,8 @@ filesystem that rounds file times, `put_if_match` and `delete_if_match` raise 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, and only there does a write reclaim an empty directory in +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. @@ -161,22 +192,26 @@ as mixins a backend's test class adds (`ConditionalPutSuite`, `KeyAndDirectorySu methods, and through the async methods on one event loop, so the two surfaces meet one contract. `StoreSuite.test_state_machine` drives random sequences of `put`, `put_if_absent`, `put_if_match`, -`delete`, `delete_if_match`, `delete_dir` and listings through random views, and checks every step against a +`put_many`, `delete`, `delete_if_match`, `delete_many`, `delete_dir` and listings through random views, and checks every step against a dict model (`zarr_storage.testing._stateful.StoreMachine`), again through both surfaces. After every -step, each stored key reads back as the model says, and `get_if_changed` with its generation is -`Unchanged`. The obstore +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. ## Configuration -No global configuration. Every knob (local I/O concurrency) is a constructor parameter with its -default in the signature. +No global configuration. Every knob (local I/O concurrency, how many requests an obstore batch +keeps in flight) is a constructor parameter with its default in the signature. ## 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. +- Sync batches over obstore run one request at a time; a thread pool, or a native batch call, + would overlap them. +- `get_ranges_into`, `put_from`, and a GPU direct storage backend whose `get_into_many` submits one + cuFile batch. ## Iterations diff --git a/packages/zarr-storage/changes/460.feature.md b/packages/zarr-storage/changes/460.feature.md index 8195140b25..31d5f7f06b 100644 --- a/packages/zarr-storage/changes/460.feature.md +++ b/packages/zarr-storage/changes/460.feature.md @@ -1 +1 @@ -Add `zarr-storage`, a new package with a Zarr-agnostic key-value storage API: a `Store` view over memory, local-filesystem and obstore backends, with sync and async methods, conditional reads and writes (`get_if_changed`, `put_if_absent`, `put_if_match`, `delete_if_match`), byte-range reads and reads into caller buffers. It ships a conformance suite in `zarr_storage.testing` that any backend can run. +Add `zarr-storage`, a new package with a Zarr-agnostic key-value storage API: a `Store` view over memory, local-filesystem and obstore backends, with sync and async methods, conditional reads and writes (`get_if_changed`, `put_if_absent`, `put_if_match`, `delete_if_match`), byte-range reads, reads into caller buffers, and batches (`get_many`, `get_into_many`, `put_many`, `delete_many`) that run concurrently where the backend can. It ships a conformance suite in `zarr_storage.testing` that any backend can run. diff --git a/packages/zarr-storage/src/zarr_storage/__init__.py b/packages/zarr-storage/src/zarr_storage/__init__.py index 2b4443c06c..cfc52eea0b 100644 --- a/packages/zarr-storage/src/zarr_storage/__init__.py +++ b/packages/zarr-storage/src/zarr_storage/__init__.py @@ -1,11 +1,13 @@ """A Zarr-agnostic key-value storage layer. A `Store` is a view of a backend at a root directory. Backends implement capability protocols -(`Readable`, `Writable`, `Listable`, and async twins) over backend paths; `Store` validates keys, -applies its root, enforces read-only access, and is the only object most callers need. +(`Readable`, `Writable`, `Listable`, their batch variants, and async twins) over backend paths; +`Store` validates keys, applies its root, enforces read-only access, and is the only object most +callers need. """ from zarr_storage._errors import ( + BatchError, InvalidByteRangeError, InvalidKeyError, KeyConflictError, @@ -24,10 +26,16 @@ ReadableAsync, ReadableInto, ReadableIntoAsync, + ReadableIntoMany, + ReadableIntoManyAsync, + ReadableMany, + ReadableManyAsync, Writable, WritableAsync, WritableIfMatch, WritableIfMatchAsync, + WritableMany, + WritableManyAsync, ) from zarr_storage._store import Store from zarr_storage._types import ( @@ -53,6 +61,7 @@ __all__ = [ "Backend", + "BatchError", "ByteRange", "Copied", "DeletableIfMatch", @@ -79,6 +88,10 @@ "ReadableAsync", "ReadableInto", "ReadableIntoAsync", + "ReadableIntoMany", + "ReadableIntoManyAsync", + "ReadableMany", + "ReadableManyAsync", "Rejected", "StorageError", "Store", @@ -90,5 +103,7 @@ "WritableAsync", "WritableIfMatch", "WritableIfMatchAsync", + "WritableMany", + "WritableManyAsync", "Written", ] diff --git a/packages/zarr-storage/src/zarr_storage/_batch.py b/packages/zarr-storage/src/zarr_storage/_batch.py new file mode 100644 index 0000000000..e850519e57 --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/_batch.py @@ -0,0 +1,111 @@ +"""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, 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 Executor, Future + +__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]], + executor: Executor | None = None, + window: int = 1, +) -> Iterator[tuple[int, R]]: + """Call `fn(*request)` for each request: one at a time, or on `executor`, `window` at once.""" + if executor is None: + return _run_serially(fn, requests) + return _run_on(executor, 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( + executor: Executor, + 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[executor.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 + finally: + for future in pending: + future.cancel() + if errors: + raise ExceptionGroup(_MESSAGE, errors) + + +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/_errors.py b/packages/zarr-storage/src/zarr_storage/_errors.py index 9303456d4c..fb47ea55d1 100644 --- a/packages/zarr-storage/src/zarr_storage/_errors.py +++ b/packages/zarr-storage/src/zarr_storage/_errors.py @@ -1,8 +1,14 @@ -"""The errors a store raises. A missing key is not one of them: reads return `None`.""" +"""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", @@ -42,3 +48,43 @@ class StoreClosedError(StorageError): 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/_protocols.py b/packages/zarr-storage/src/zarr_storage/_protocols.py index f9855e5deb..783dc60690 100644 --- a/packages/zarr-storage/src/zarr_storage/_protocols.py +++ b/packages/zarr-storage/src/zarr_storage/_protocols.py @@ -11,11 +11,17 @@ implements whichever it can; `Store`'s 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`. + +The batch capabilities (`ReadableMany`, `ReadableIntoMany`, `WritableMany` and their async twins) +are optional and change only speed: `Store.get_many` and its siblings work on any backend that +can read or write, one operation at a time, and use a backend's batch methods when it has them. A +batch method yields `(index, result)` pairs as operations finish and follows the failure rule of +`zarr_storage._batch`, whose runners implement it. """ from __future__ import annotations -from typing import TYPE_CHECKING, Protocol, TypeVar +from typing import TYPE_CHECKING, Protocol, TypeVar, runtime_checkable if TYPE_CHECKING: from collections.abc import AsyncIterator, Iterator, Sequence @@ -45,10 +51,16 @@ "ReadableAsync", "ReadableInto", "ReadableIntoAsync", + "ReadableIntoMany", + "ReadableIntoManyAsync", + "ReadableMany", + "ReadableManyAsync", "Writable", "WritableAsync", "WritableIfMatch", "WritableIfMatchAsync", + "WritableMany", + "WritableManyAsync", ] @@ -143,6 +155,35 @@ def delete_if_match(self, path: str, generation: Generation) -> Deleted | Reject ... +@runtime_checkable +class ReadableMany(Backend, Protocol): + def get_many( + self, requests: Sequence[tuple[str, ByteRange | None]] + ) -> 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]): + def get_into_many( + self, requests: Sequence[tuple[str, O_contra, ByteRange | None]] + ) -> Iterator[tuple[int, Copied | Missing]]: + """`get_into` for each `(path, out, byte_range)`, yielding `(index, result)`.""" + ... + + +@runtime_checkable +class WritableMany(Backend, Protocol): + def put_many(self, requests: Sequence[tuple[str, memoryview]]) -> Iterator[tuple[int, Written]]: + """`put` for each `(path, value)`, yielding `(index, result)` as each finishes.""" + ... + + def delete_many(self, paths: Sequence[str]) -> Iterator[tuple[int, Deleted | Missing]]: + """`delete` for each path, yielding `(index, result)` as each finishes.""" + ... + + class Listable(Backend, Protocol): def list(self, directory: str) -> Iterator[str]: """Every key under `directory`, as backend paths, in no particular order.""" @@ -195,6 +236,31 @@ async def delete_if_match_async( ) -> Deleted | Rejected | Missing: ... +@runtime_checkable +class ReadableManyAsync(Backend, Protocol): + def get_many_async( + self, requests: Sequence[tuple[str, ByteRange | None]] + ) -> AsyncIterator[tuple[int, Found | Missing]]: ... + + +@runtime_checkable +class ReadableIntoManyAsync(Backend, Protocol[O_contra]): + def get_into_many_async( + self, requests: Sequence[tuple[str, O_contra, ByteRange | None]] + ) -> AsyncIterator[tuple[int, Copied | Missing]]: ... + + +@runtime_checkable +class WritableManyAsync(Backend, Protocol): + def put_many_async( + self, requests: Sequence[tuple[str, memoryview]] + ) -> AsyncIterator[tuple[int, Written]]: ... + + def delete_many_async( + self, paths: Sequence[str] + ) -> AsyncIterator[tuple[int, Deleted | Missing]]: ... + + class ListableAsync(Backend, Protocol): def list_async(self, directory: str) -> AsyncIterator[str]: ... diff --git a/packages/zarr-storage/src/zarr_storage/_store.py b/packages/zarr-storage/src/zarr_storage/_store.py index 84171819ff..e445bfa61e 100644 --- a/packages/zarr-storage/src/zarr_storage/_store.py +++ b/packages/zarr-storage/src/zarr_storage/_store.py @@ -6,16 +6,26 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Final, Generic, Self, TypeVar, final +from collections.abc import AsyncGenerator, Generator +from typing import TYPE_CHECKING, Final, Generic, Self, TypeVar, cast, final +from zarr_storage._batch import run_many, run_many_async from zarr_storage._buffers import byte_view -from zarr_storage._errors import ReadOnlyError, StoreClosedError +from zarr_storage._errors import BatchError, ReadOnlyError, StoreClosedError from zarr_storage._keys import check_key, is_within, join, normalize_directory, relativize -from zarr_storage._protocols import Backend +from zarr_storage._protocols import ( + Backend, + ReadableIntoMany, + ReadableIntoManyAsync, + ReadableMany, + ReadableManyAsync, + WritableMany, + WritableManyAsync, +) from zarr_storage._types import Missing if TYPE_CHECKING: - from collections.abc import AsyncIterator, Iterator, Sequence + from collections.abc import AsyncIterator, Iterable, Iterator, Sequence from types import TracebackType from typing_extensions import Buffer @@ -53,6 +63,9 @@ B_co = TypeVar("B_co", bound=Backend, covariant=True) O = TypeVar("O") T = TypeVar("T") +R = TypeVar("R") +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.""" @final @@ -203,6 +216,99 @@ def _writable_directory(self, directory: str) -> str: raise ReadOnlyError(f"{self!r} is read-only.") 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.""" + self._check_open() + if self._read_only: + raise ReadOnlyError(f"{self!r} is read-only.") + paths = [self._writable_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) + return paths + + 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() + + async def _streamed_async( + 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 + 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)] + + @staticmethod + async def _finished_async( + 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)] + # ----------------------------------------------------------------- sync reads def get( @@ -286,6 +392,81 @@ def delete_dir(self: Store[Writable], directory: str = "") -> None: """Delete every key under `directory` (by default, every key in this store).""" self._backend.delete_dir(self._writable_directory(directory)) + # ----------------------------------------------------------------- sync 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 happen as the pairs are taken, 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)) + return self._streamed(batch, run_many(backend.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)) + return self._streamed(batch, run_many(backend.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`). + """ + batch = list(items) + keys = [key for key, _ in batch] + paths = self._writable_paths(keys) + requests = [ + (path, byte_view(value, writable=False)) + for path, (_, value) in zip(paths, batch, strict=True) + ] + backend = self._backend + if isinstance(backend, WritableMany): + return self._finished(keys, backend.put_many(requests)) + return self._finished(keys, run_many(backend.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)) + return self._finished(batch, run_many(backend.delete, [(path,) for path in paths])) + # ----------------------------------------------------------------- sync listing def list(self: Store[Listable], directory: str = "") -> Iterator[str]: @@ -385,6 +566,63 @@ async def delete_dir_async(self: Store[WritableAsync], directory: str = "") -> N """Async `delete_dir`.""" await self._backend.delete_dir_async(self._writable_directory(directory)) + # ----------------------------------------------------------------- async batches + + def get_many_async( + self: Store[ReadableAsync], requests: Iterable[Q] + ) -> AsyncIterator[tuple[Q, Found | Missing]]: + """Async `get_many`.""" + 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_async(batch, backend.get_many_async(paths)) + return self._streamed_async(batch, run_many_async(backend.get_async, paths)) + + def get_into_many_async( + self: Store[ReadableIntoAsync[O]], + requests: Iterable[tuple[str, O] | tuple[str, O, ByteRange | None]], + ) -> AsyncIterator[tuple[tuple[str, O] | tuple[str, O, ByteRange | None], Copied | Missing]]: + """Async `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_async(batch, many.get_into_many_async(paths)) + return self._streamed_async(batch, run_many_async(backend.get_into_async, paths)) + + async def put_many_async( + self: Store[WritableAsync], items: Iterable[tuple[str, Buffer]] + ) -> list[tuple[str, Written]]: + """Async `put_many`.""" + batch = list(items) + keys = [key for key, _ in batch] + paths = self._writable_paths(keys) + requests = [ + (path, byte_view(value, writable=False)) + for path, (_, value) in zip(paths, batch, strict=True) + ] + backend = self._backend + if isinstance(backend, WritableManyAsync): + return await self._finished_async(keys, backend.put_many_async(requests)) + return await self._finished_async(keys, run_many_async(backend.put_async, requests)) + + async def delete_many_async( + self: Store[WritableAsync], keys: Iterable[str] + ) -> list[tuple[str, Deleted | Missing]]: + """Async `delete_many`.""" + batch = list(keys) + paths = self._writable_paths(batch) + backend = self._backend + if isinstance(backend, WritableManyAsync): + return await self._finished_async(batch, backend.delete_many_async(paths)) + return await self._finished_async( + batch, run_many_async(backend.delete_async, [(path,) for path in paths]) + ) + # ----------------------------------------------------------------- async listing def list_async(self: Store[ListableAsync], directory: str = "") -> AsyncIterator[str]: @@ -397,6 +635,21 @@ def list_dir_async(self: Store[ListableAsync], directory: str = "") -> AsyncIter return self._open_items_async(self._backend.list_dir_async(self._directory(directory))) +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/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index c2ee719bb1..45a3f93dc5 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -17,6 +17,7 @@ from pathlib import Path from typing import TYPE_CHECKING, ParamSpec, TypedDict, TypeVar +from zarr_storage._batch import run_many, run_many_async from zarr_storage._buffers import byte_view from zarr_storage._byte_range import resolve from zarr_storage._errors import ( @@ -396,7 +397,8 @@ class LocalBackend: Create `root` if it doesn't exist. With `create=False`, a missing root raises `FileNotFoundError`. concurrency - The number of threads that run the async methods' file operations. + The number of threads that run the async methods' file operations, and the number of + operations a batch (`get_many`, `put_many`, ...) runs at once. """ def __init__( @@ -704,6 +706,24 @@ def list_dir(self, directory: str) -> Iterator[ListItem]: return iter(()) return _classify(entries) + # --- batches: the operations above, `concurrency` at once on the backend's threads + + def get_many( + self, requests: Sequence[tuple[str, ByteRange | None]] + ) -> Iterator[tuple[int, Found | Missing]]: + return run_many(self.get, requests, self._pool(), self._concurrency) + + def get_into_many( + self, requests: Sequence[tuple[str, Buffer, ByteRange | None]] + ) -> Iterator[tuple[int, Copied | Missing]]: + return run_many(self.get_into, requests, self._pool(), self._concurrency) + + def put_many(self, requests: Sequence[tuple[str, memoryview]]) -> Iterator[tuple[int, Written]]: + return run_many(self.put, requests, self._pool(), self._concurrency) + + def delete_many(self, paths: Sequence[str]) -> Iterator[tuple[int, Deleted | Missing]]: + return run_many(self.delete, [(path,) for path in paths], self._pool(), self._concurrency) + # --- async twins: run the sync methods on the backend's threads def _pool(self) -> ThreadPoolExecutor: @@ -763,6 +783,26 @@ async def delete_if_match_async( async def delete_dir_async(self, directory: str) -> None: await self._run(self.delete_dir, directory) + def get_many_async( + self, requests: Sequence[tuple[str, ByteRange | None]] + ) -> AsyncIterator[tuple[int, Found | Missing]]: + return run_many_async(self.get_async, requests, self._concurrency) + + def get_into_many_async( + self, requests: Sequence[tuple[str, Buffer, ByteRange | None]] + ) -> AsyncIterator[tuple[int, Copied | Missing]]: + return run_many_async(self.get_into_async, requests, self._concurrency) + + def put_many_async( + self, requests: Sequence[tuple[str, memoryview]] + ) -> AsyncIterator[tuple[int, Written]]: + return run_many_async(self.put_async, requests, self._concurrency) + + def delete_many_async( + self, paths: Sequence[str] + ) -> AsyncIterator[tuple[int, Deleted | Missing]]: + return run_many_async(self.delete_async, [(path,) for path in paths], self._concurrency) + async def list_async(self, directory: str) -> AsyncIterator[str]: for path in await self._run(_materialize, self.list(directory)): yield path diff --git a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py index f8dcc61664..0bdb8fbae4 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py @@ -24,6 +24,7 @@ ) from obstore.store import HTTPStore, LocalStore +from zarr_storage._batch import run_many_async from zarr_storage._buffers import byte_view, copy_into from zarr_storage._byte_range import resolve from zarr_storage._errors import InvalidKeyError, KeyConflictError, UnsupportedOperationError @@ -61,6 +62,9 @@ _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.""" @@ -263,10 +267,18 @@ class ObjectStoreBackend: The obstore store. writable Whether to accept writes. Defaults to `False` for `HTTPStore`, `True` otherwise. + concurrency + The number of requests an async batch (`get_many_async`, `put_many_async`, ...) keeps in + flight. Sync batches run one request at a time. """ - def __init__(self, store: ObjectStore, *, writable: bool | None = None) -> None: + def __init__( + self, store: ObjectStore, *, writable: bool | None = None, concurrency: int = 32 + ) -> None: + if concurrency < 1: + raise ValueError(f"concurrency must be >= 1; got {concurrency}.") self._store = store + self._concurrency = concurrency 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) @@ -307,6 +319,19 @@ async def _under_a_key_async(self, path: str) -> bool: 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 ( @@ -382,8 +407,8 @@ def head(self, path: str) -> ObjectMetadata | Missing: return _metadata(obstore.head(self._store, path)) except FileNotFoundError: return Missing(time.time()) - except GenericError: - if self._under_a_key(path): + except GenericError as e: + if self._refused_under_a_key(e, path): return Missing(time.time()) raise @@ -392,8 +417,8 @@ async def head_async(self, path: str) -> ObjectMetadata | Missing: return _metadata(await obstore.head_async(self._store, path)) except FileNotFoundError: return Missing(time.time()) - except GenericError: - if await self._under_a_key_async(path): + except GenericError as e: + if await self._refused_under_a_key_async(e, path): return Missing(time.time()) raise @@ -496,8 +521,8 @@ def _read_whole_and_slice( result = obstore.get(self._store, path) except FileNotFoundError: return Missing(time.time()) - except GenericError: - if self._under_a_key(path): + 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"]) @@ -537,8 +562,8 @@ async def _read_whole_and_slice_async( result = await obstore.get_async(self._store, path) except FileNotFoundError: return Missing(time.time()) - except GenericError: - if await self._under_a_key_async(path): + 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"]) @@ -691,6 +716,28 @@ async def delete_dir_async(self, directory: str) -> None: with contextlib.suppress(FileNotFoundError): await obstore.delete_async(self._store, path) + # --- async batches: the async operations, `concurrency` at once + + def get_many_async( + self, requests: Sequence[tuple[str, ByteRange | None]] + ) -> AsyncIterator[tuple[int, Found | Missing]]: + return run_many_async(self.get_async, requests, self._concurrency) + + def get_into_many_async( + self, requests: Sequence[tuple[str, Buffer, ByteRange | None]] + ) -> AsyncIterator[tuple[int, Copied | Missing]]: + return run_many_async(self.get_into_async, requests, self._concurrency) + + def put_many_async( + self, requests: Sequence[tuple[str, memoryview]] + ) -> AsyncIterator[tuple[int, Written]]: + return run_many_async(self.put_async, requests, self._concurrency) + + def delete_many_async( + self, paths: Sequence[str] + ) -> AsyncIterator[tuple[int, Deleted | Missing]]: + return run_many_async(self.delete_async, [(path,) for path in paths], self._concurrency) + # --- Listable def _paths(self, directory: str) -> Iterator[str]: diff --git a/packages/zarr-storage/src/zarr_storage/testing/_api.py b/packages/zarr-storage/src/zarr_storage/testing/_api.py index ec05ed7b0a..df6ba9241f 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/_api.py +++ b/packages/zarr-storage/src/zarr_storage/testing/_api.py @@ -7,7 +7,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Protocol, Self, cast +from typing import TYPE_CHECKING, Protocol, Self, TypeVar, cast from typing_extensions import Buffer @@ -26,7 +26,7 @@ if TYPE_CHECKING: import asyncio - from collections.abc import AsyncIterator, Iterator, Sequence + from collections.abc import AsyncIterator, Iterable, Iterator, Sequence from types import TracebackType from zarr_storage._protocols import DeletableIfMatch, DeletableIfMatchAsync @@ -48,6 +48,9 @@ __all__ = ["AsyncAPI", "FullBackend", "StoreAPI", "delete_if_match", "unwrap"] +T = TypeVar("T") +Q = TypeVar("Q", bound="str | tuple[str, ByteRange | None]") + class FullBackend( Readable, @@ -95,6 +98,14 @@ def put_if_match( ) -> 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: ... @@ -125,7 +136,7 @@ def delete_if_match( return cast("Store[DeletableIfMatch]", store).delete_if_match(key, generation) -async def _next(items: AsyncIterator[object]) -> object: +async def _next(items: AsyncIterator[T]) -> T: return await anext(items) @@ -197,14 +208,31 @@ def delete_if_match(self, key: str, generation: Generation) -> Deleted | Rejecte def delete_dir(self, directory: str = "") -> None: self._runner.run(self._store.delete_dir_async(directory)) + def get_many(self, requests: Iterable[Q]) -> Iterator[tuple[Q, Found | Missing]]: + # `get_many_async` checks its requests when called; the results come one at a time. + return self._iterate(self._store.get_many_async(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_async(requests)) + + def put_many(self, items: Iterable[tuple[str, Buffer]]) -> list[tuple[str, Written]]: + return self._runner.run(self._store.put_many_async(items)) + + def delete_many(self, keys: Iterable[str]) -> list[tuple[str, Deleted | Missing]]: + return self._runner.run(self._store.delete_many_async(keys)) + def list(self, directory: str = "") -> Iterator[str]: # `list_async` checks its argument when called; the items come one at a time. - return self._iterate(self._store.list_async(directory)) # pyright: ignore[reportReturnType] + return self._iterate(self._store.list_async(directory)) def list_dir(self, directory: str = "") -> Iterator[ListItem]: - return self._iterate(self._store.list_dir_async(directory)) # pyright: ignore[reportReturnType] + return self._iterate(self._store.list_dir_async(directory)) - def _iterate(self, items: AsyncIterator[object]) -> Iterator[object]: + def _iterate(self, items: AsyncIterator[T]) -> Iterator[T]: while True: try: yield self._runner.run(_next(items)) diff --git a/packages/zarr-storage/src/zarr_storage/testing/_stateful.py b/packages/zarr-storage/src/zarr_storage/testing/_stateful.py index b762245455..627e880e43 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/_stateful.py +++ b/packages/zarr-storage/src/zarr_storage/testing/_stateful.py @@ -2,7 +2,7 @@ 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 and conditional writes meet present keys, not just absent ones. Generations that a write or +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. """ @@ -15,7 +15,7 @@ from hypothesis import strategies as st from hypothesis.stateful import RuleBasedStateMachine, initialize, invariant, precondition, rule -from zarr_storage._errors import KeyConflictError +from zarr_storage._errors import BatchError, KeyConflictError from zarr_storage._keys import join from zarr_storage._types import ( Deleted, @@ -64,6 +64,11 @@ 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 @@ -120,6 +125,12 @@ def _check_refused(self, result: object, path: str) -> None: 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" @@ -200,6 +211,49 @@ def put_if_match_retired(self, data: st.DataObject, value: bytes) -> None: 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) @@ -278,6 +332,14 @@ 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) diff --git a/packages/zarr-storage/src/zarr_storage/testing/_suite.py b/packages/zarr-storage/src/zarr_storage/testing/_suite.py index 3dc4d60c3b..0976c3a4e2 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/_suite.py +++ b/packages/zarr-storage/src/zarr_storage/testing/_suite.py @@ -15,6 +15,7 @@ import pickle import threading import time +from collections import Counter from dataclasses import dataclass from functools import partial from typing import TYPE_CHECKING, Literal @@ -25,6 +26,7 @@ from hypothesis.stateful import run_state_machine_as_test from zarr_storage._errors import ( + BatchError, InvalidByteRangeError, InvalidKeyError, KeyConflictError, @@ -168,6 +170,21 @@ class IfChangedCase: 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", @@ -322,6 +339,16 @@ 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, @@ -329,6 +356,8 @@ def _missing_get_if_changed(store: StoreAPI) -> object: _missing_get_if_changed, _missing_get_ranges, _missing_get_into, + _missing_get_many, + _missing_get_into_many, _missing_head, ] MISSING_READ_IDS = [ @@ -338,6 +367,8 @@ def _missing_get_if_changed(store: StoreAPI) -> object: "get_if_changed", "get_ranges", "get_into", + "get_many", + "get_into_many", "head", ] @@ -355,8 +386,27 @@ def _delete_dir(store: StoreAPI) -> object: return None -WRITES: list[Callable[[StoreAPI], object]] = [_put, _delete, _delete_dir] -WRITE_IDS = ["put", "delete", "delete_dir"] +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: @@ -375,6 +425,14 @@ 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() @@ -391,6 +449,10 @@ def _list_dir(store: StoreAPI) -> object: _put, _delete, _delete_dir, + _get_many, + _get_into_many, + _put_many, + _delete_many, _list, _list_dir, ] @@ -402,11 +464,48 @@ def _list_dir(store: StoreAPI) -> object: "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: @@ -715,6 +814,98 @@ def test_delete_dir(self, store: StoreAPI, directory: str, remaining: set[str]) 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) @@ -825,11 +1016,16 @@ def test_use_after_owner_closes_raises( with pytest.raises(StoreClosedError): operation(view) - @pytest.mark.parametrize("listing", ["list", "list_dir"]) + @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 = store.list() if listing == "list" else store.list_dir() + 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)) @@ -973,6 +1169,16 @@ def test_directory_under_a_key_raises(self, store: StoreAPI) -> None: 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) diff --git a/packages/zarr-storage/tests/test_batch.py b/packages/zarr-storage/tests/test_batch.py new file mode 100644 index 0000000000..40b6b43c9b --- /dev/null +++ b/packages/zarr-storage/tests/test_batch.py @@ -0,0 +1,111 @@ +"""The runners behind every batch: windows, ordering and the failure rule.""" + +from __future__ import annotations + +import asyncio +import threading +import time +from concurrent.futures import ThreadPoolExecutor +from typing import TYPE_CHECKING + +import pytest + +from zarr_storage import BatchError +from zarr_storage._batch import run_many, run_many_async + +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": + with ThreadPoolExecutor(8) as executor: + into.extend(run_many(tracker, requests, executor, window)) + 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.""" + 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 tracker.started == set(range(window)) + assert sorted(results) == [(x, x * x) for x in range(1, window)] + + +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/test_store.py b/packages/zarr-storage/tests/test_store.py index c8d098e1bd..c2a54602c9 100644 --- a/packages/zarr-storage/tests/test_store.py +++ b/packages/zarr-storage/tests/test_store.py @@ -7,6 +7,7 @@ import pytest from zarr_storage import ( + BatchError, Copied, Found, FoundRanges, @@ -18,12 +19,13 @@ Store, SuffixRequest, Unchanged, + Written, ) from zarr_storage._byte_range import resolve from zarr_storage.backends import MemoryBackend if TYPE_CHECKING: - from collections.abc import Sequence + from collections.abc import Iterator, Sequence from zarr_storage import ByteRange @@ -109,6 +111,96 @@ def test_get_into_a_device_buffer(byte_range: ByteRange | None, expected: bytes) 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]] + ) -> 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) / "r" + 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) / "r" + 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)) @@ -116,6 +208,10 @@ def _static_buffer_checks(host: Store[MemoryBackend], device: Store[_DeviceBacke 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: From ce26c8f0632c94998f9419eac4aa4eba506be9ad Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 17 Nov 2026 22:40:44 +0100 Subject: [PATCH 06/31] feat(zarr-storage)!: split Store into Store and AsyncStore Store keeps the sync operations; the new AsyncStore offers the same operations under the same names as coroutines and async iterators (`await astore.get(k)`, `async for k in astore.list()`), so neither class carries the other's methods. Both derive from a private _View that holds the backend, root, read-only flag and ownership, and does key validation, root joining and read-only checks once. `store.as_async()` and `astore.as_sync()` are non-owning views on the same backend. Lifecycle differs between the two: Store has close() and `with`; AsyncStore has `await aclose()` and `async with`, which awaits a ClosableAsync backend's aclose (new capability, for cleanup that awaits a client session) and calls close on any other. LocalBackend gains aclose, running its pool shutdown on a worker thread. BREAKING CHANGE: Store's `*_async` methods are gone; use `store.as_async()` or construct an AsyncStore. Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-storage/DESIGN.md | 40 +- packages/zarr-storage/changes/460.feature.md | 2 +- .../zarr-storage/src/zarr_storage/__init__.py | 14 +- .../src/zarr_storage/_protocols.py | 17 +- .../zarr-storage/src/zarr_storage/_store.py | 371 +++++++++++------- .../src/zarr_storage/backends/_local.py | 4 + .../src/zarr_storage/testing/_api.py | 74 ++-- .../src/zarr_storage/testing/_suite.py | 10 +- packages/zarr-storage/tests/test_obstore.py | 8 +- packages/zarr-storage/tests/test_store.py | 82 ++++ 10 files changed, 413 insertions(+), 209 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index bbc31cacfd..46edd3d635 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -25,22 +25,32 @@ Sources, and what each contributed: ## Shape ``` -Backend capability protocols over backend paths; owns shared state and lifecycle +Backend capability protocols over backend paths; owns shared state and lifecycle ▲ -Store one concrete class: (backend, root, read_only, owner); validates keys, applies the root, - relativizes listings, enforces read-only; `store / "a"` is a view on the same backend +_View (backend, root, read_only, owner): validates keys, applies the root, relativizes + ▲ listings, enforces read-only; `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`, `Writable`, -`Listable`, `WritableIfMatch`, `DeletableIfMatch`, and their async twins) on *backend paths*: `/`-separated strings, already joined with the root. Backends never -see relative keys and never join or strip paths. They hold everything that must exist once: the dict, +`Listable`, `WritableIfMatch`, `DeletableIfMatch`, and their async twins) on *backend paths*: +`/`-separated strings, already joined with the root. Backends never see relative keys and never join or strip paths. They hold everything that must exist once: the dict, the filesystem root, a client, locks, concurrency limits. -A **`Store`** is the only class users hold. It is a view: a backend plus a root. All key validation, -root joining, listing relativization and read-only enforcement happen in `Store`, 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, +A **`Store`** or **`AsyncStore`** is the only object users hold. Each is a view: a backend plus a +root. All key validation, root joining, listing relativization and read-only enforcement 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, 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 with both surfaces 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 @@ -53,7 +63,7 @@ get them wrong on its own (the source of most bugs in the legacy API: #2190, #24 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 (sync; each has an `_async` twin) +## Operations (`Store`; `AsyncStore` has each under the same name, as a coroutine or async iterator) | Method | Returns | Notes | |---|---|---| @@ -131,10 +141,11 @@ raises `InvalidByteRangeError`; a suffix longer than the value returns the whole ## Views, lifecycle, identity -- `store / "a"` and `store.with_read_only(True)` return views on the same backend. A view of a +- `store / "a"`, `store.with_read_only(True)` and `store.as_async()` (or `as_sync()`) return views + on the same backend. A view of a read-only store is read-only; `with_read_only(False)` on one raises `ReadOnlyError`. -- The store the user constructed owns the backend. `close()` on it closes the backend; on a derived - view it does nothing. After the backend closes, every view raises `StoreClosedError`. +- The store the user constructed owns the backend. `close()` (`aclose()` on an `AsyncStore`) on it + closes the backend; on a derived view it does nothing. After the backend closes, every view raises `StoreClosedError`. - No value equality: `==` is identity. `shares_backend(other)` and `overlaps(other)` answer the questions callers actually ask. - Pickling carries the backend's configuration and the view's root. A pickled memory store carries a @@ -188,8 +199,9 @@ writes that concurrently create and remove the same directories can surface its `zarr_storage.testing.StoreSuite` holds the contract every backend meets; optional capabilities come as mixins a backend's test class adds (`ConditionalPutSuite`, `KeyAndDirectorySuite`, `PickleSuite`, ...) or their refusing counterparts (`NoConditionalPutSuite`, -`KeyDirectoryConflictSuite`, `ConditionalRaceSuite`, ...). Every test runs twice: through the sync -methods, and through the async methods on one event loop, so the two surfaces meet one contract. +`KeyDirectoryConflictSuite`, `ConditionalRaceSuite`, ...). 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 diff --git a/packages/zarr-storage/changes/460.feature.md b/packages/zarr-storage/changes/460.feature.md index 31d5f7f06b..618fe3e1d8 100644 --- a/packages/zarr-storage/changes/460.feature.md +++ b/packages/zarr-storage/changes/460.feature.md @@ -1 +1 @@ -Add `zarr-storage`, a new package with a Zarr-agnostic key-value storage API: a `Store` view over memory, local-filesystem and obstore backends, with sync and async methods, conditional reads and writes (`get_if_changed`, `put_if_absent`, `put_if_match`, `delete_if_match`), byte-range reads, reads into caller buffers, and batches (`get_many`, `get_into_many`, `put_many`, `delete_many`) that run concurrently where the backend can. It ships a conformance suite in `zarr_storage.testing` that any backend can run. +Add `zarr-storage`, a new package with a Zarr-agnostic key-value storage API: `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 (`get_if_changed`, `put_if_absent`, `put_if_match`, `delete_if_match`), byte-range reads, reads into caller buffers, and batches (`get_many`, `get_into_many`, `put_many`, `delete_many`) that run concurrently where the backend can. It ships a conformance suite in `zarr_storage.testing` that any backend can run. diff --git a/packages/zarr-storage/src/zarr_storage/__init__.py b/packages/zarr-storage/src/zarr_storage/__init__.py index cfc52eea0b..510c1e6ef0 100644 --- a/packages/zarr-storage/src/zarr_storage/__init__.py +++ b/packages/zarr-storage/src/zarr_storage/__init__.py @@ -1,9 +1,10 @@ """A Zarr-agnostic key-value storage layer. -A `Store` is a view of a backend at a root directory. Backends implement capability protocols -(`Readable`, `Writable`, `Listable`, their batch variants, and async twins) over backend paths; -`Store` validates keys, applies its root, enforces read-only access, and is the only object most -callers need. +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, and are the only +objects most callers need. """ from zarr_storage._errors import ( @@ -18,6 +19,7 @@ ) from zarr_storage._protocols import ( Backend, + ClosableAsync, DeletableIfMatch, DeletableIfMatchAsync, Listable, @@ -37,7 +39,7 @@ WritableMany, WritableManyAsync, ) -from zarr_storage._store import Store +from zarr_storage._store import AsyncStore, Store from zarr_storage._types import ( ByteRange, Copied, @@ -60,9 +62,11 @@ ) __all__ = [ + "AsyncStore", "Backend", "BatchError", "ByteRange", + "ClosableAsync", "Copied", "DeletableIfMatch", "DeletableIfMatchAsync", diff --git a/packages/zarr-storage/src/zarr_storage/_protocols.py b/packages/zarr-storage/src/zarr_storage/_protocols.py index 783dc60690..7058b87ca7 100644 --- a/packages/zarr-storage/src/zarr_storage/_protocols.py +++ b/packages/zarr-storage/src/zarr_storage/_protocols.py @@ -8,8 +8,8 @@ `/`. Each capability has a sync protocol and an async twin whose methods end in `_async`. A backend -implements whichever it can; `Store`'s 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 +implements whichever it can. `Store` calls the sync protocols and `AsyncStore` the async ones, and +their 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`. The batch capabilities (`ReadableMany`, `ReadableIntoMany`, `WritableMany` and their async twins) @@ -43,6 +43,7 @@ __all__ = [ "Backend", + "ClosableAsync", "DeletableIfMatch", "DeletableIfMatchAsync", "Listable", @@ -86,6 +87,18 @@ def close(self) -> None: ... +@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): def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: """The value at `path`, or the requested part of it.""" diff --git a/packages/zarr-storage/src/zarr_storage/_store.py b/packages/zarr-storage/src/zarr_storage/_store.py index e445bfa61e..de7dedc71b 100644 --- a/packages/zarr-storage/src/zarr_storage/_store.py +++ b/packages/zarr-storage/src/zarr_storage/_store.py @@ -1,7 +1,7 @@ -"""`Store`: a view of a backend at a root. +"""`Store` and `AsyncStore`: views of a backend at a root, through sync methods or coroutines. -`Store` is 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 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. """ from __future__ import annotations @@ -15,6 +15,7 @@ from zarr_storage._keys import check_key, is_within, join, normalize_directory, relativize from zarr_storage._protocols import ( Backend, + ClosableAsync, ReadableIntoMany, ReadableIntoManyAsync, ReadableMany, @@ -58,7 +59,7 @@ Written, ) -__all__ = ["Store"] +__all__ = ["AsyncStore", "Store"] B_co = TypeVar("B_co", bound=Backend, covariant=True) O = TypeVar("O") @@ -68,30 +69,8 @@ """A `get_many` request: a key, or a key and the part of its value to read.""" -@final -class Store(Generic[B_co]): - """A backend seen from a root directory. - - Construct a store from a backend; the store you construct owns the backend and closes it. - `store / "a"` and `with_read_only()` 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. - - `backend` gives direct access to the backend, which bypasses the key grammar, the root, and - read-only and closed checks. - - Stores have no value equality: `==` is identity. Use `shares_backend` and `overlaps` to compare - stores. - - Parameters - ---------- - backend - The backend to read and write through. - root - The directory within the backend that this store's keys are relative to. - read_only - Refuse writes through this store. A backend that can't write makes every store over it - read-only. - """ +class _View(Generic[B_co]): + """What `Store` and `AsyncStore` share: a backend, a root, read-only access, ownership.""" __slots__ = ("_backend", "_owner", "_read_only", "_root") @@ -144,11 +123,11 @@ def with_read_only(self, read_only: bool = True) -> Self: raise ReadOnlyError(f"{self!r} is read-only; its views are read-only too.") return self._view(root=self._root, read_only=read_only) - def shares_backend(self, other: Store[Backend]) -> bool: + def shares_backend(self, other: _View[Backend]) -> bool: """Whether `other` reads and writes through the same backend object.""" return self._backend is other._backend - def overlaps(self, other: Store[Backend]) -> bool: + def overlaps(self, other: _View[Backend]) -> bool: """Whether a key could be visible through both stores: same backend, nested roots.""" return self.shares_backend(other) and ( is_within(self._root, other._root) or is_within(other._root, self._root) @@ -161,24 +140,6 @@ def __repr__(self) -> str: def __reduce__(self) -> tuple[object, ...]: return (_restore_store, (type(self), self._backend, self._root, self._read_only)) - # ----------------------------------------------------------------- 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() - # ----------------------------------------------------------------- path handling def _check_open(self) -> None: @@ -246,6 +207,66 @@ def _writable_paths(self, keys: Sequence[str]) -> list[str]: seen.add(path) return paths + +@final +class Store(_View[B_co]): + """A backend seen from a root directory, through sync methods. + + Construct a store from a backend; the store you construct owns the backend and closes it. + `store / "a"`, `with_read_only()` 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. + + `backend` gives direct access to the backend, which bypasses the key grammar, the root, and + read-only and closed checks. + + Stores have no value equality: `==` is identity. Use `shares_backend` and `overlaps` to compare + stores. + + Parameters + ---------- + backend + The backend to read and write through. + root + The directory within the backend that this store's keys are relative to. + read_only + Refuse writes through this store. A backend that can't write makes every store over it + read-only. + """ + + __slots__ = () + + def __init__(self, backend: B_co, *, root: str = "", read_only: bool = False) -> None: + super().__init__(backend, root=root, read_only=read_only) + + def as_async(self) -> AsyncStore[B_co]: + """An `AsyncStore` view on the same backend and root; it doesn't own the backend.""" + view = AsyncStore(self._backend, root=self._root, read_only=self._read_only) + view._owner = False + return view + + # ----------------------------------------------------------------- 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 results + def _streamed( self, batch: Sequence[T], results: Iterator[tuple[int, R]] ) -> Iterator[tuple[T, R]]: @@ -268,25 +289,6 @@ def _streamed( if isinstance(results, Generator): results.close() - async def _streamed_async( - 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 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.""" @@ -297,19 +299,7 @@ def _finished(batch: Sequence[T], results: Iterator[tuple[int, R]]) -> list[tupl raise _batch_error(group, batch, completed, completed.keys()) from None return [(request, completed[index]) for index, request in enumerate(batch)] - @staticmethod - async def _finished_async( - 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)] - - # ----------------------------------------------------------------- sync reads + # ----------------------------------------------------------------- reads def get( self: Store[Readable], key: str, *, byte_range: ByteRange | None = None @@ -355,7 +345,7 @@ def exists(self: Store[Readable], key: str) -> bool: """Whether `key` holds a value.""" return not isinstance(self.head(key), Missing) - # ----------------------------------------------------------------- sync writes + # ----------------------------------------------------------------- writes def put(self: Store[Writable], key: str, value: Buffer) -> Written: """Write `value` at `key`.""" @@ -392,7 +382,7 @@ def delete_dir(self: Store[Writable], directory: str = "") -> None: """Delete every key under `directory` (by default, every key in this store).""" self._backend.delete_dir(self._writable_directory(directory)) - # ----------------------------------------------------------------- sync batches + # ----------------------------------------------------------------- batches def get_many( self: Store[Readable], requests: Iterable[Q] @@ -467,7 +457,7 @@ def delete_many( return self._finished(batch, backend.delete_many(paths)) return self._finished(batch, run_many(backend.delete, [(path,) for path in paths])) - # ----------------------------------------------------------------- sync listing + # ----------------------------------------------------------------- listing def list(self: Store[Listable], directory: str = "") -> Iterator[str]: """Every key under `directory`, relative to this store's root, in no particular order. @@ -486,118 +476,209 @@ def list_dir(self: Store[Listable], directory: str = "") -> Iterator[ListItem]: """ return self._open_items(self._backend.list_dir(self._directory(directory))) - # ----------------------------------------------------------------- async reads - async def get_async( - self: Store[ReadableAsync], key: str, *, byte_range: ByteRange | None = None +@final +class AsyncStore(_View[B_co]): + """A backend seen from a root directory, through coroutines. + + The async twin of `Store`: the same operations under the same names, awaited, over the + backend's async capabilities (`ReadableAsync`, `WritableAsync`, ...). Listings and lazy batches + are async iterators. Construct one from a 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. + root + The directory within the backend that this store's keys are relative to. + read_only + Refuse writes through this store. A backend that can't write makes every store over it + read-only. + """ + + __slots__ = () + + def __init__(self, backend: B_co, *, root: str = "", read_only: bool = False) -> None: + super().__init__(backend, root=root, read_only=read_only) + + def as_sync(self) -> Store[B_co]: + """A `Store` view on the same backend and root; it doesn't own the backend.""" + view = Store(self._backend, root=self._root, read_only=self._read_only) + view._owner = False + return view + + # ----------------------------------------------------------------- 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 results + + 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)] + + # ----------------------------------------------------------------- reads + + async def get( + self: AsyncStore[ReadableAsync], key: str, *, byte_range: ByteRange | None = None ) -> Found | Missing: - """Async `get`.""" + """As `Store.get`.""" return await self._backend.get_async(self._path(key), byte_range) - async def get_if_changed_async( - self: Store[ReadableAsync], + async def get_if_changed( + self: AsyncStore[ReadableAsync], key: str, generation: Generation, *, byte_range: ByteRange | None = None, ) -> Found | Missing | Unchanged: - """Async `get_if_changed`.""" + """As `Store.get_if_changed`.""" return await self._backend.get_if_changed_async(self._path(key), generation, byte_range) - async def get_ranges_async( - self: Store[ReadableAsync], key: str, ranges: Sequence[ByteRange] + async def get_ranges( + self: AsyncStore[ReadableAsync], key: str, ranges: Sequence[ByteRange] ) -> FoundRanges | Missing: - """Async `get_ranges`.""" + """As `Store.get_ranges`.""" return await self._backend.get_ranges_async(self._path(key), ranges) - async def get_into_async( - self: Store[ReadableIntoAsync[O]], + async def get_into( + self: AsyncStore[ReadableIntoAsync[O]], key: str, out: O, *, byte_range: ByteRange | None = None, ) -> Copied | Missing: - """Async `get_into`.""" + """As `Store.get_into`.""" return await self._backend.get_into_async(self._path(key), out, byte_range) - async def head_async(self: Store[ReadableAsync], key: str) -> ObjectMetadata | Missing: - """Async `head`.""" + async def head(self: AsyncStore[ReadableAsync], key: str) -> ObjectMetadata | Missing: + """As `Store.head`.""" return await self._backend.head_async(self._path(key)) - async def exists_async(self: Store[ReadableAsync], key: str) -> bool: - """Async `exists`.""" - return not isinstance(await self.head_async(key), Missing) + async def exists(self: AsyncStore[ReadableAsync], key: str) -> bool: + """As `Store.exists`.""" + return not isinstance(await self.head(key), Missing) - # ----------------------------------------------------------------- async writes + # ----------------------------------------------------------------- writes - async def put_async(self: Store[WritableAsync], key: str, value: Buffer) -> Written: - """Async `put`.""" + async def put(self: AsyncStore[WritableAsync], key: str, value: Buffer) -> Written: + """As `Store.put`.""" return await self._backend.put_async( self._writable_path(key), byte_view(value, writable=False) ) - async def put_if_absent_async( - self: Store[WritableAsync], key: str, value: Buffer + async def put_if_absent( + self: AsyncStore[WritableAsync], key: str, value: Buffer ) -> Written | Rejected: - """Async `put_if_absent`.""" + """As `Store.put_if_absent`.""" return await self._backend.put_if_absent_async( self._writable_path(key), byte_view(value, writable=False) ) - async def put_if_match_async( - self: Store[WritableIfMatchAsync], key: str, value: Buffer, generation: Generation + async def put_if_match( + self: AsyncStore[WritableIfMatchAsync], key: str, value: Buffer, generation: Generation ) -> Written | Rejected | Missing: - """Async `put_if_match`.""" + """As `Store.put_if_match`.""" return await self._backend.put_if_match_async( self._writable_path(key), byte_view(value, writable=False), generation ) - async def delete_async(self: Store[WritableAsync], key: str) -> Deleted | Missing: - """Async `delete`.""" + async def delete(self: AsyncStore[WritableAsync], key: str) -> Deleted | Missing: + """As `Store.delete`.""" return await self._backend.delete_async(self._writable_path(key)) - async def delete_if_match_async( - self: Store[DeletableIfMatchAsync], key: str, generation: Generation + async def delete_if_match( + self: AsyncStore[DeletableIfMatchAsync], key: str, generation: Generation ) -> Deleted | Rejected | Missing: - """Async `delete_if_match`.""" + """As `Store.delete_if_match`.""" return await self._backend.delete_if_match_async(self._writable_path(key), generation) - async def delete_dir_async(self: Store[WritableAsync], directory: str = "") -> None: - """Async `delete_dir`.""" + async def delete_dir(self: AsyncStore[WritableAsync], directory: str = "") -> None: + """As `Store.delete_dir`.""" await self._backend.delete_dir_async(self._writable_directory(directory)) - # ----------------------------------------------------------------- async batches + # ----------------------------------------------------------------- batches - def get_many_async( - self: Store[ReadableAsync], requests: Iterable[Q] + def get_many( + self: AsyncStore[ReadableAsync], requests: Iterable[Q] ) -> AsyncIterator[tuple[Q, Found | Missing]]: - """Async `get_many`.""" + """As `Store.get_many`.""" 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_async(batch, backend.get_many_async(paths)) - return self._streamed_async(batch, run_many_async(backend.get_async, paths)) + return self._streamed(batch, backend.get_many_async(paths)) + return self._streamed(batch, run_many_async(backend.get_async, paths)) - def get_into_many_async( - self: Store[ReadableIntoAsync[O]], + def get_into_many( + self: AsyncStore[ReadableIntoAsync[O]], requests: Iterable[tuple[str, O] | tuple[str, O, ByteRange | None]], ) -> AsyncIterator[tuple[tuple[str, O] | tuple[str, O, ByteRange | None], Copied | Missing]]: - """Async `get_into_many`.""" + """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_async(batch, many.get_into_many_async(paths)) - return self._streamed_async(batch, run_many_async(backend.get_into_async, paths)) + return self._streamed(batch, many.get_into_many_async(paths)) + return self._streamed(batch, run_many_async(backend.get_into_async, paths)) - async def put_many_async( - self: Store[WritableAsync], items: Iterable[tuple[str, Buffer]] + async def put_many( + self: AsyncStore[WritableAsync], items: Iterable[tuple[str, Buffer]] ) -> list[tuple[str, Written]]: - """Async `put_many`.""" + """As `Store.put_many`.""" batch = list(items) keys = [key for key, _ in batch] paths = self._writable_paths(keys) @@ -607,31 +688,31 @@ async def put_many_async( ] backend = self._backend if isinstance(backend, WritableManyAsync): - return await self._finished_async(keys, backend.put_many_async(requests)) - return await self._finished_async(keys, run_many_async(backend.put_async, requests)) + return await self._finished(keys, backend.put_many_async(requests)) + return await self._finished(keys, run_many_async(backend.put_async, requests)) - async def delete_many_async( - self: Store[WritableAsync], keys: Iterable[str] + async def delete_many( + self: AsyncStore[WritableAsync], keys: Iterable[str] ) -> list[tuple[str, Deleted | Missing]]: - """Async `delete_many`.""" + """As `Store.delete_many`.""" batch = list(keys) paths = self._writable_paths(batch) backend = self._backend if isinstance(backend, WritableManyAsync): - return await self._finished_async(batch, backend.delete_many_async(paths)) - return await self._finished_async( + return await self._finished(batch, backend.delete_many_async(paths)) + return await self._finished( batch, run_many_async(backend.delete_async, [(path,) for path in paths]) ) - # ----------------------------------------------------------------- async listing + # ----------------------------------------------------------------- listing - def list_async(self: Store[ListableAsync], directory: str = "") -> AsyncIterator[str]: - """Async `list`.""" + def list(self: AsyncStore[ListableAsync], directory: str = "") -> AsyncIterator[str]: + """As `Store.list`.""" paths = self._backend.list_async(self._directory(directory)) return self._open_items_async(_relativized(paths, self._root)) - def list_dir_async(self: Store[ListableAsync], directory: str = "") -> AsyncIterator[ListItem]: - """Async `list_dir`.""" + def list_dir(self: AsyncStore[ListableAsync], directory: str = "") -> AsyncIterator[ListItem]: + """As `Store.list_dir`.""" return self._open_items_async(self._backend.list_dir_async(self._directory(directory))) @@ -656,6 +737,6 @@ async def _relativized(paths: AsyncIterator[str], root: str) -> AsyncIterator[st def _restore_store( - cls: type[Store[Backend]], backend: Backend, root: str, read_only: bool -) -> Store[Backend]: + cls: type[_View[Backend]], backend: Backend, root: str, read_only: bool +) -> _View[Backend]: return cls(backend, root=root, read_only=read_only) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index 45a3f93dc5..e6a22f68eb 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -455,6 +455,10 @@ def close(self) -> None: if executor is not None: executor.shutdown(wait=True) + async def aclose(self) -> None: + """`close` on a worker thread: it waits for running file operations to finish.""" + await asyncio.to_thread(self.close) + # --- paths def _file(self, path: str) -> Path: diff --git a/packages/zarr-storage/src/zarr_storage/testing/_api.py b/packages/zarr-storage/src/zarr_storage/testing/_api.py index df6ba9241f..49ca4415e6 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/_api.py +++ b/packages/zarr-storage/src/zarr_storage/testing/_api.py @@ -1,7 +1,7 @@ -"""The store surface the suite tests, and an adapter that drives it through the async methods. +"""The store surface the suite tests, and an adapter that drives it through `AsyncStore`. -Every suite test runs twice: once against `Store`'s sync methods, once against `AsyncAPI`, which -gives the same sync-looking surface but performs every call through the matching `_async` method on +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. """ @@ -23,6 +23,7 @@ WritableIfMatch, WritableIfMatchAsync, ) +from zarr_storage._store import AsyncStore if TYPE_CHECKING: import asyncio @@ -46,7 +47,7 @@ Written, ) -__all__ = ["AsyncAPI", "FullBackend", "StoreAPI", "delete_if_match", "unwrap"] +__all__ = ["AsyncAPI", "FullBackend", "StoreAPI", "async_api", "delete_if_match", "unwrap"] T = TypeVar("T") Q = TypeVar("Q", bound="str | tuple[str, ByteRange | None]") @@ -121,9 +122,9 @@ def __exit__( def unwrap(store: StoreAPI) -> Store[FullBackend]: - """The `Store` behind a `StoreAPI`.""" + """The `Store` behind a `StoreAPI`: a sync view of an `AsyncAPI`'s store.""" if isinstance(store, AsyncAPI): - return store.store + return store.store.as_sync() return store # pyright: ignore[reportReturnType] @@ -140,15 +141,24 @@ 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 its root.""" + return AsyncAPI(AsyncStore(store.backend, root=store.root, read_only=store.read_only), runner) + + class AsyncAPI: - """`Store`'s sync-looking surface, performed through its `_async` methods on one event loop.""" + """`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: Store[FullBackend], runner: asyncio.Runner) -> None: + def __init__(self, store: AsyncStore[FullBackend], runner: asyncio.Runner) -> None: self._store = store self._runner = runner @property - def store(self) -> Store[FullBackend]: + def store(self) -> AsyncStore[FullBackend]: return self._store @property @@ -164,73 +174,71 @@ 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_async(key, byte_range=byte_range)) + 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_async(key, generation, byte_range=byte_range) - ) + 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_async(key, ranges)) + 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_async(key, out, byte_range=byte_range)) + 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_async(key)) + return self._runner.run(self._store.head(key)) def exists(self, key: str) -> bool: - return self._runner.run(self._store.exists_async(key)) + return self._runner.run(self._store.exists(key)) def put(self, key: str, value: Buffer) -> Written: - return self._runner.run(self._store.put_async(key, value)) + 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_async(key, value)) + 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_async(key, value, generation)) + 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_async(key)) + return self._runner.run(self._store.delete(key)) def delete_if_match(self, key: str, generation: Generation) -> Deleted | Rejected | Missing: - store = cast("Store[DeletableIfMatchAsync]", self._store) - return self._runner.run(store.delete_if_match_async(key, generation)) + 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_async(directory)) + self._runner.run(self._store.delete_dir(directory)) def get_many(self, requests: Iterable[Q]) -> Iterator[tuple[Q, Found | Missing]]: - # `get_many_async` checks its requests when called; the results come one at a time. - return self._iterate(self._store.get_many_async(requests)) + # `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_async(requests)) + 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_async(items)) + 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_async(keys)) + return self._runner.run(self._store.delete_many(keys)) def list(self, directory: str = "") -> Iterator[str]: - # `list_async` checks its argument when called; the items come one at a time. - return self._iterate(self._store.list_async(directory)) + # `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_async(directory)) + return self._iterate(self._store.list_dir(directory)) def _iterate(self, items: AsyncIterator[T]) -> Iterator[T]: while True: @@ -246,7 +254,7 @@ def with_read_only(self, read_only: bool = True) -> Self: return type(self)(self._store.with_read_only(read_only), self._runner) def close(self) -> None: - self._store.close() + self._runner.run(self._store.aclose()) def __enter__(self) -> Self: return self diff --git a/packages/zarr-storage/src/zarr_storage/testing/_suite.py b/packages/zarr-storage/src/zarr_storage/testing/_suite.py index 0976c3a4e2..7a36a9a7ce 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/_suite.py +++ b/packages/zarr-storage/src/zarr_storage/testing/_suite.py @@ -3,7 +3,7 @@ `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 the sync methods and through the async methods (see `AsyncAPI`). +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. """ @@ -50,7 +50,7 @@ Unchanged, Written, ) -from zarr_storage.testing._api import AsyncAPI, FullBackend, StoreAPI, delete_if_match, unwrap +from zarr_storage.testing._api import FullBackend, StoreAPI, async_api, delete_if_match, unwrap from zarr_storage.testing._stateful import Capabilities, StoreMachine if TYPE_CHECKING: @@ -582,7 +582,7 @@ def _machine_store( runner: asyncio.Runner, ) -> StoreAPI: store = suite.make_store(directories.mktemp("machine")) - return store if api == "sync" else AsyncAPI(store, runner) + return store if api == "sync" else async_api(store, runner) # ---------------------------------------------------------------------------- the core suite @@ -605,7 +605,7 @@ def store(self, request: pytest.FixtureRequest, tmp_path: Path) -> Iterator[Stor yield store return with asyncio.Runner() as runner: - yield AsyncAPI(store, runner) + yield async_api(store, runner) # ------------------------------------------------------------------ everything at once @@ -762,7 +762,7 @@ def test_get_ranges_reads_one_generation(self, tmp_path: Path, api: str) -> None writer.start() try: with asyncio.Runner() as runner: - reader: StoreAPI = store if api == "sync" else AsyncAPI(store, 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) diff --git a/packages/zarr-storage/tests/test_obstore.py b/packages/zarr-storage/tests/test_obstore.py index 6321cbb625..213203297a 100644 --- a/packages/zarr-storage/tests/test_obstore.py +++ b/packages/zarr-storage/tests/test_obstore.py @@ -131,15 +131,15 @@ async def _collect(items: AsyncIterator[object]) -> list[object]: def _list_a_async(store: Store[ObjectStoreBackend]) -> object: - return asyncio.run(_collect(store.list_async("a"))) + return asyncio.run(_collect(store.as_async().list("a"))) def _list_dir_a_async(store: Store[ObjectStoreBackend]) -> object: - return asyncio.run(_collect(store.list_dir_async("a"))) + return asyncio.run(_collect(store.as_async().list_dir("a"))) def _get_ab_async(store: Store[ObjectStoreBackend]) -> object: - return asyncio.run(store.get_async("a/b")) + return asyncio.run(store.as_async().get("a/b")) @pytest.mark.parametrize( @@ -190,5 +190,5 @@ def test_get_if_changed_without_if_none_match_is_unchanged( if api == "sync": result = store.get_if_changed("k", generation) else: - result = asyncio.run(store.get_if_changed_async("k", generation)) + result = asyncio.run(store.as_async().get_if_changed("k", generation)) assert result == Unchanged(generation, result.read_at) diff --git a/packages/zarr-storage/tests/test_store.py b/packages/zarr-storage/tests/test_store.py index c2a54602c9..63582e5066 100644 --- a/packages/zarr-storage/tests/test_store.py +++ b/packages/zarr-storage/tests/test_store.py @@ -2,11 +2,13 @@ from __future__ import annotations +import asyncio from typing import TYPE_CHECKING import pytest from zarr_storage import ( + AsyncStore, BatchError, Copied, Found, @@ -253,3 +255,83 @@ def test_byte_range_out_of_order_raises(make: object) -> None: 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() + store = Store(backend, root=root, read_only=read_only) + 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() + assert not backend.closed + store.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] + AsyncStore(_ReadOnlyBackend({})).get("k") # pyright: ignore[reportAttributeAccessIssue] From e2c9ab3aded8cac07aafc908b37be1b6c29aed83 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Wed, 18 Nov 2026 11:11:16 +0100 Subject: [PATCH 07/31] feat(zarr-storage)!: share thread pools and operation limits across backends Add two resources that backends share, after TensorStore's context resources: ThreadPool runs blocking work, and Limiter caps operations in flight for threads and tasks on any event loop in one first-come, first-served queue. Pass one to several backends to bound them together; left out, a backend uses a process-wide default (ThreadPool.default(), max(4, cpu_count) threads; one Limiter(32) per obstore store class). LocalBackend takes `threads` and runs async operations and batches on it; closing the backend no longer shuts a pool down, since whoever creates a pool owns it. ObjectStoreBackend takes `concurrency`, a Limiter, and holds a slot for every operation, sync and async, single and batched, instead of bounding each async batch on its own. A slot is re-entrant within one operation, so an operation that calls another can't wait on itself. A batch started on one of its pool's own threads runs on that thread rather than wait on the pool. Pickling keeps resources shared: pickle stores each object once, and defaults unpickle as the receiving process's defaults. BREAKING CHANGE: LocalBackend's `concurrency: int` is now `threads: ThreadPool`, and ObjectStoreBackend's `concurrency` is a Limiter instead of an int. LocalBackend.aclose is gone. Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-storage/DESIGN.md | 49 ++- .../zarr-storage/src/zarr_storage/__init__.py | 3 + .../zarr-storage/src/zarr_storage/_batch.py | 20 +- .../src/zarr_storage/_resources.py | 364 ++++++++++++++++++ .../src/zarr_storage/backends/_local.py | 95 +++-- .../src/zarr_storage/backends/_obstore.py | 295 ++++++++------ packages/zarr-storage/tests/test_batch.py | 9 +- packages/zarr-storage/tests/test_local.py | 5 - packages/zarr-storage/tests/test_resources.py | 299 ++++++++++++++ 9 files changed, 940 insertions(+), 199 deletions(-) create mode 100644 packages/zarr-storage/src/zarr_storage/_resources.py create mode 100644 packages/zarr-storage/tests/test_resources.py diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 46edd3d635..62ace954e5 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -35,8 +35,10 @@ AsyncStore the same names as coroutines; `aclose()`, `async with`; `as_sync()` A **backend** is an object that implements some capability protocols (`Readable`, `Writable`, `Listable`, `WritableIfMatch`, `DeletableIfMatch`, and their async twins) on *backend paths*: -`/`-separated strings, already joined with the root. Backends never see relative keys and never join or strip paths. They hold everything that must exist once: the dict, -the filesystem root, a client, locks, concurrency limits. +`/`-separated strings, already joined with the root. 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. Thread pools and limits on operations in flight are shared +resources the backend is given (see below). A **`Store`** or **`AsyncStore`** is the only object users hold. Each is a view: a backend plus a root. All key validation, root joining, listing relativization and read-only enforcement happen in @@ -166,10 +168,12 @@ key (`a/b` when `a` is a key): that reads as absent. | `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` runs batches, sync and -async, `concurrency` operations at once on its threads; `ObjectStoreBackend` keeps `concurrency` -requests of an async batch in flight and runs sync batches one request at a time; `MemoryBackend` -uses `Store`'s serial batches, which are as fast for it. +Every backend has `put_if_absent` and `get_if_changed`. `LocalBackend` runs its async operations +and its batches, sync and async, on its `threads`, as many batch operations at once as the pool has +threads. `ObjectStoreBackend` holds a slot of its `concurrency` limiter for every operation, sync +and async, single and batched; async batches start at most `concurrency.limit` operations at once, +and sync batches run one at a time. `MemoryBackend` uses `Store`'s serial batches, which are as fast +for it. `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 @@ -210,10 +214,39 @@ step, each stored key reads back as the model says, through `get` and `get_many` `get_if_changed` with its generation is `Unchanged`. The obstore tests also fail any async run that makes a blocking obstore call. +## Shared resources + +Threads and limits on operations in flight are resources that backends share, after TensorStore's +context resources (`file_io_concurrency`, `s3_request_concurrency`). zarrs has no I/O limits of its +own (its `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. + +- `ThreadPool(max_workers)` runs blocking work: `LocalBackend(root, threads=...)`. +- `Limiter(limit)` caps operations in flight, for threads and tasks on any event loop in one + first-come, first-served queue: `ObjectStoreBackend(store, concurrency=...)`. `limiter.slot()` is + a sync or async context manager. A slot is held for a whole operation, and an operation that calls + another through a limiter it already holds takes no second slot (a context variable records the + slots an operation holds), so `get_into`, which reads through `get`, can't wait on itself. +- Pass one resource to several backends to bound them together. Left out, a backend uses a + process-wide default, as TensorStore does: `ThreadPool.default()` of `max(4, cpu_count)` threads, + and one `Limiter(32)` per obstore store class, so every S3 backend in a process shares one limit + and an HTTP backend doesn't share it. A default is shared state, but it changes only speed, never + what an operation does; pass your own resource to isolate a backend. +- Whoever creates a resource owns it: a backend never shuts down a pool it was given, and closing a + `LocalBackend` refuses new operations without stopping the pool. The default pool can't be shut + down. +- Pickling a resource pickles its settings, and pickle stores each object once, so backends that + shared a resource share one new resource after a round trip; a default unpickles as the receiving + process's default. +- A batch started on one of its pool's own threads runs on that thread, one operation at a time: + waiting there for work queued on the same pool could wait forever once every thread does it. +- Thread 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. + ## Configuration -No global configuration. Every knob (local I/O concurrency, how many requests an obstore batch -keeps in flight) is a constructor parameter with its default in the signature. +No global configuration. Every knob is a constructor parameter with its default in the signature; +the shared resources above are passed the same way. ## Open diff --git a/packages/zarr-storage/src/zarr_storage/__init__.py b/packages/zarr-storage/src/zarr_storage/__init__.py index 510c1e6ef0..d18fb9ee4a 100644 --- a/packages/zarr-storage/src/zarr_storage/__init__.py +++ b/packages/zarr-storage/src/zarr_storage/__init__.py @@ -39,6 +39,7 @@ WritableMany, WritableManyAsync, ) +from zarr_storage._resources import Limiter, ThreadPool from zarr_storage._store import AsyncStore, Store from zarr_storage._types import ( ByteRange, @@ -79,6 +80,7 @@ "InvalidKeyError", "Key", "KeyConflictError", + "Limiter", "ListItem", "Listable", "ListableAsync", @@ -101,6 +103,7 @@ "Store", "StoreClosedError", "SuffixRequest", + "ThreadPool", "Unchanged", "UnsupportedOperationError", "Writable", diff --git a/packages/zarr-storage/src/zarr_storage/_batch.py b/packages/zarr-storage/src/zarr_storage/_batch.py index e850519e57..c3a9145599 100644 --- a/packages/zarr-storage/src/zarr_storage/_batch.py +++ b/packages/zarr-storage/src/zarr_storage/_batch.py @@ -14,7 +14,9 @@ if TYPE_CHECKING: from collections.abc import AsyncIterator, Callable, Coroutine, Iterator, Sequence - from concurrent.futures import Executor, Future + from concurrent.futures import Future + + from zarr_storage._resources import ThreadPool __all__ = ["run_many", "run_many_async"] @@ -27,13 +29,17 @@ def run_many( fn: Callable[[Unpack[Ts]], R], requests: Sequence[tuple[*Ts]], - executor: Executor | None = None, + pool: ThreadPool | None = None, window: int = 1, ) -> Iterator[tuple[int, R]]: - """Call `fn(*request)` for each request: one at a time, or on `executor`, `window` at once.""" - if executor is None: + """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(executor, fn, requests, window) + return _run_on(pool, fn, requests, window) def _run_serially( @@ -48,7 +54,7 @@ def _run_serially( def _run_on( - executor: Executor, + pool: ThreadPool, fn: Callable[[Unpack[Ts]], R], requests: Sequence[tuple[*Ts]], window: int, @@ -59,7 +65,7 @@ def _run_on( try: while pending or (not errors and started < len(requests)): while not errors and started < len(requests) and len(pending) < window: - pending[executor.submit(fn, *requests[started])] = started + pending[pool.submit(fn, *requests[started])] = started started += 1 done, _ = wait(pending, return_when=FIRST_COMPLETED) for future in done: diff --git a/packages/zarr-storage/src/zarr_storage/_resources.py b/packages/zarr-storage/src/zarr_storage/_resources.py new file mode 100644 index 0000000000..5f4671e01b --- /dev/null +++ b/packages/zarr-storage/src/zarr_storage/_resources.py @@ -0,0 +1,364 @@ +"""Resources that backends share: thread pools and limits on operations in flight. + +Modeled on TensorStore's context resources (`file_io_concurrency`, `s3_request_concurrency`): a +resource is an object you create and pass to as many backends as should share it. A backend never +closes a resource it was given. Left out, a backend uses a process-wide default, as TensorStore +does, because threads and request slots are process-wide in the end; pass your own to isolate a +backend from the rest of the process. A resource changes how fast operations run, never what they +do. + +Pickling a resource pickles its settings. Pickle stores each object once, so backends that shared +a resource before pickling share one new resource after; a default resource unpickles as the +default of the receiving process. +""" + +from __future__ import annotations + +import asyncio +import os +import threading +from collections import deque +from concurrent.futures import ThreadPoolExecutor +from contextvars import ContextVar +from functools import partial +from typing import TYPE_CHECKING, Final, TypeVar, TypeVarTuple + +if TYPE_CHECKING: + from collections.abc import Callable + from concurrent.futures import Future + from contextvars import Token + from types import TracebackType + +__all__ = ["Limiter", "Slot", "ThreadPool", "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, for the backends given it. + + The threads start when first needed. Whoever creates a pool owns it and may `shutdown` it once + no backend 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 that backends use when given none.""" + 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; the batch runners 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.""" + return self._pool().submit(fn, *args) + + async def run(self, fn: Callable[[*Ts], R], /, *args: *Ts) -> R: + """Await `fn(*args)`, run on one of the pool's threads.""" + loop = asyncio.get_running_loop() + return await loop.run_in_executor(self._pool(), partial(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.") + + +_default_pool_lock = threading.Lock() +_default_pool: list[ThreadPool] = [] + + +def default_thread_pool() -> ThreadPool: + """The process-wide `ThreadPool`, with `DEFAULT_THREADS` threads.""" + with _default_pool_lock: + if not _default_pool: + _default_pool.append(_DefaultThreadPool(DEFAULT_THREADS)) + return _default_pool[0] + + +# ---------------------------------------------------------------------------- limiters + +_held: ContextVar[frozenset[Limiter]] = ContextVar( + "zarr_storage_held_limiters", default=frozenset() +) +"""The limiters whose slots the current operation holds, so nested operations don't wait again.""" + + +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 + + +class Limiter: + """A limit on how many operations run at once, across every backend given it. + + Threads and tasks on any event loop wait in one first-come, first-served queue. + + Parameters + ---------- + limit + The most operations that run at once. + """ + + def __init__(self, limit: int) -> None: + _check_size("limit", limit) + self._limit = limit + self._lock = threading.Lock() + self._in_use = 0 + self._waiters: deque[_ThreadWaiter | _TaskWaiter] = deque() + + @property + def limit(self) -> int: + return self._limit + + @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,)) + + def slot(self) -> Slot: + """A context manager, sync (`with`) or async (`async with`), that holds one slot. + + Prefer it to `acquire` and `release`: it releases on error, and inside an operation that + already holds a slot of this limiter it takes no second one, so an operation that calls + another can't wait on itself. + """ + 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, blocking the calling thread until one is free.""" + with self._lock: + if self._take(): + return + waiter = _ThreadWaiter() + self._waiters.append(waiter) + waiter.wait() + + async def acquire_async(self) -> None: + """Take a slot, waiting without blocking the event loop until one is free.""" + 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, 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 + + +class Slot: + """One use of a `Limiter`: holds a slot from entry to exit, unless the operation holds one.""" + + __slots__ = ("_limiter", "_token") + + def __init__(self, limiter: Limiter) -> None: + self._limiter = limiter + self._token: Token[frozenset[Limiter]] | None = None + + def _needed(self) -> bool: + return self._limiter not in _held.get() + + def _mark(self) -> None: + self._token = _held.set(_held.get() | {self._limiter}) + + def _unmark(self) -> None: + if self._token is None: + return + _held.reset(self._token) + self._token = None + self._limiter.release() + + def __enter__(self) -> None: + if self._needed(): + self._limiter.acquire() + self._mark() + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self._unmark() + + async def __aenter__(self) -> None: + if self._needed(): + await self._limiter.acquire_async() + self._mark() + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self._unmark() + + +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_lock = threading.Lock() +_default_limiters: dict[str, Limiter] = {} + + +def default_limiter(key: str) -> Limiter: + """The process-wide `Limiter` for `key` (such as an obstore store class), of `DEFAULT_LIMIT`.""" + with _default_limiters_lock: + limiter = _default_limiters.get(key) + if limiter is None: + limiter = _default_limiters[key] = _DefaultLimiter(key) + return limiter diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index e6a22f68eb..5545ce5f02 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -2,7 +2,6 @@ from __future__ import annotations -import asyncio import contextlib import errno import os @@ -12,10 +11,8 @@ import threading import time import uuid -from concurrent.futures import ThreadPoolExecutor -from functools import partial from pathlib import Path -from typing import TYPE_CHECKING, ParamSpec, TypedDict, TypeVar +from typing import TYPE_CHECKING, TypedDict, TypeVar, TypeVarTuple from zarr_storage._batch import run_many, run_many_async from zarr_storage._buffers import byte_view @@ -26,6 +23,7 @@ StoreClosedError, UnsupportedOperationError, ) +from zarr_storage._resources import ThreadPool, default_thread_pool from zarr_storage._types import ( Copied, Deleted, @@ -73,14 +71,14 @@ ) _WINDOWS_FORBIDDEN_CHARACTERS = frozenset('<>:"\\|?*') | frozenset(chr(i) for i in range(32)) -P = ParamSpec("P") +Ts = TypeVarTuple("Ts") R = TypeVar("R") T = TypeVar("T") class _State(TypedDict): root: str - concurrency: int + threads: ThreadPool closed: bool @@ -396,24 +394,26 @@ class LocalBackend: create Create `root` if it doesn't exist. With `create=False`, a missing root raises `FileNotFoundError`. - concurrency - The number of threads that run the async methods' file operations, and the number of - operations a batch (`get_many`, `put_many`, ...) runs at once. + threads + The threads that run the async methods' file operations and the operations of batches + (`get_many`, `put_many`, ...), which run as many at once as the pool has threads. Share one + pool between backends to bound their threads together; the default is the process-wide + `ThreadPool.default()`. The backend never shuts the pool down. """ def __init__( - self, root: str | os.PathLike[str], *, create: bool = True, concurrency: int = 16 + self, + root: str | os.PathLike[str], + *, + create: bool = True, + threads: ThreadPool | None = None, ) -> None: - if concurrency < 1: - raise ValueError(f"concurrency must be >= 1; got {concurrency}.") self._root = Path(root).resolve() if create: self._root.mkdir(parents=True, exist_ok=True) elif not self._root.is_dir(): raise FileNotFoundError(f"The root directory {str(self._root)!r} does not exist.") - self._concurrency = concurrency - self._executor: ThreadPoolExecutor | None = None - self._executor_lock = threading.Lock() + self._threads = default_thread_pool() if threads is None else threads self._probe_lock = threading.Lock() self._exact_times: bool | None = None self._closed = False @@ -423,17 +423,20 @@ def root(self) -> Path: """The directory that holds the keys.""" return self._root + @property + def threads(self) -> ThreadPool: + """The threads that run the async methods and batches.""" + return self._threads + def __repr__(self) -> str: return f"LocalBackend({str(self._root)!r})" def __getstate__(self) -> _State: - return {"root": str(self._root), "concurrency": self._concurrency, "closed": self._closed} + return {"root": str(self._root), "threads": self._threads, "closed": self._closed} def __setstate__(self, state: _State) -> None: self._root = Path(state["root"]) - self._concurrency = state["concurrency"] - self._executor = None - self._executor_lock = threading.Lock() + self._threads = state["threads"] self._probe_lock = threading.Lock() self._exact_times = None self._closed = state["closed"] @@ -449,15 +452,8 @@ def writable(self) -> bool: return True def close(self) -> None: - with self._executor_lock: - self._closed = True - executor, self._executor = self._executor, None - if executor is not None: - executor.shutdown(wait=True) - - async def aclose(self) -> None: - """`close` on a worker thread: it waits for running file operations to finish.""" - await asyncio.to_thread(self.close) + """Refuse further operations. Operations already running finish; the pool stays up.""" + self._closed = True # --- paths @@ -710,39 +706,38 @@ def list_dir(self, directory: str) -> Iterator[ListItem]: return iter(()) return _classify(entries) - # --- batches: the operations above, `concurrency` at once on the backend's threads + # --- batches: the operations above, as many at once as the pool has threads def get_many( self, requests: Sequence[tuple[str, ByteRange | None]] ) -> Iterator[tuple[int, Found | Missing]]: - return run_many(self.get, requests, self._pool(), self._concurrency) + return run_many(self.get, requests, self._open_threads(), self._threads.max_workers) def get_into_many( self, requests: Sequence[tuple[str, Buffer, ByteRange | None]] ) -> Iterator[tuple[int, Copied | Missing]]: - return run_many(self.get_into, requests, self._pool(), self._concurrency) + return run_many(self.get_into, requests, self._open_threads(), self._threads.max_workers) def put_many(self, requests: Sequence[tuple[str, memoryview]]) -> Iterator[tuple[int, Written]]: - return run_many(self.put, requests, self._pool(), self._concurrency) + return run_many(self.put, requests, self._open_threads(), self._threads.max_workers) def delete_many(self, paths: Sequence[str]) -> Iterator[tuple[int, Deleted | Missing]]: - return run_many(self.delete, [(path,) for path in paths], self._pool(), self._concurrency) + return run_many( + self.delete, + [(path,) for path in paths], + self._open_threads(), + self._threads.max_workers, + ) # --- async twins: run the sync methods on the backend's threads - def _pool(self) -> ThreadPoolExecutor: - with self._executor_lock: - if self._closed: - raise StoreClosedError(f"{self!r} is closed.") - if self._executor is None: - self._executor = ThreadPoolExecutor( - max_workers=self._concurrency, thread_name_prefix="zarr-storage-local" - ) - return self._executor + def _open_threads(self) -> ThreadPool: + if self._closed: + raise StoreClosedError(f"{self!r} is closed.") + return self._threads - async def _run(self, fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: - loop = asyncio.get_running_loop() - return await loop.run_in_executor(self._pool(), partial(fn, *args, **kwargs)) + async def _run(self, fn: Callable[[*Ts], T], *args: *Ts) -> T: + return await self._open_threads().run(fn, *args) async def get_async(self, path: str, byte_range: ByteRange | None) -> Found | Missing: return await self._run(self.get, path, byte_range) @@ -790,22 +785,24 @@ async def delete_dir_async(self, directory: str) -> None: def get_many_async( self, requests: Sequence[tuple[str, ByteRange | None]] ) -> AsyncIterator[tuple[int, Found | Missing]]: - return run_many_async(self.get_async, requests, self._concurrency) + return run_many_async(self.get_async, requests, self._threads.max_workers) def get_into_many_async( self, requests: Sequence[tuple[str, Buffer, ByteRange | None]] ) -> AsyncIterator[tuple[int, Copied | Missing]]: - return run_many_async(self.get_into_async, requests, self._concurrency) + return run_many_async(self.get_into_async, requests, self._threads.max_workers) def put_many_async( self, requests: Sequence[tuple[str, memoryview]] ) -> AsyncIterator[tuple[int, Written]]: - return run_many_async(self.put_async, requests, self._concurrency) + return run_many_async(self.put_async, requests, self._threads.max_workers) def delete_many_async( self, paths: Sequence[str] ) -> AsyncIterator[tuple[int, Deleted | Missing]]: - return run_many_async(self.delete_async, [(path,) for path in paths], self._concurrency) + return run_many_async( + self.delete_async, [(path,) for path in paths], self._threads.max_workers + ) async def list_async(self, directory: str) -> AsyncIterator[str]: for path in await self._run(_materialize, self.list(directory)): diff --git a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py index 0bdb8fbae4..27e7ed771f 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py @@ -29,6 +29,7 @@ from zarr_storage._byte_range import resolve from zarr_storage._errors import InvalidKeyError, KeyConflictError, UnsupportedOperationError from zarr_storage._keys import check_key, relativize +from zarr_storage._resources import Limiter, default_limiter from zarr_storage._types import ( Deleted, Found, @@ -268,17 +269,26 @@ class ObjectStoreBackend: writable Whether to accept writes. Defaults to `False` for `HTTPStore`, `True` otherwise. concurrency - The number of requests an async batch (`get_many_async`, `put_many_async`, ...) keeps in - flight. Sync batches run one request at a time. + The limit on this backend's operations in flight, sync and async, single and batched + (listings are not counted). Share one `Limiter` between backends to bound them together. + The default is a process-wide limiter for the store's class, so that every S3 backend in + the process shares one limit, as TensorStore's `s3_request_concurrency` does. Async batches + start at most `concurrency.limit` operations at once; sync batches run one at a time. """ def __init__( - self, store: ObjectStore, *, writable: bool | None = None, concurrency: int = 32 + self, + store: ObjectStore, + *, + writable: bool | None = None, + concurrency: Limiter | None = None, ) -> None: - if concurrency < 1: - raise ValueError(f"concurrency must be >= 1; got {concurrency}.") self._store = store - self._concurrency = concurrency + self._concurrency = ( + default_limiter(f"obstore.{type(store).__name__}") + if concurrency is None + else concurrency + ) 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) @@ -289,6 +299,11 @@ def store(self) -> ObjectStore: """The obstore store.""" return self._store + @property + def concurrency(self) -> Limiter: + """The limit on this backend's operations in flight.""" + return self._concurrency + def __repr__(self) -> str: return f"ObjectStoreBackend({self._store!r})" @@ -403,59 +418,67 @@ async def _conflicts_async(self, path: str) -> bool: # --- 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): + with self._concurrency.slot(): + try: + return _metadata(obstore.head(self._store, path)) + except FileNotFoundError: return Missing(time.time()) - raise + 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): + async with self._concurrency.slot(): + try: + return _metadata(await obstore.head_async(self._store, path)) + except FileNotFoundError: return Missing(time.time()) - raise + 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, {}) + with self._concurrency.slot(): + 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, {}) + async with self._concurrency.slot(): + 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) + with self._concurrency.slot(): + 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) + async with self._concurrency.slot(): + 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) + with self._concurrency.slot(): + 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) + async with self._concurrency.slot(): + 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 @@ -486,26 +509,29 @@ async def _get_async( 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()) + with self._concurrency.slot(): + 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: @@ -531,29 +557,32 @@ def _read_whole_and_slice( 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:] + async with self._concurrency.slot(): + 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() ) - 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] @@ -573,32 +602,38 @@ async def _read_whole_and_slice_async( # --- Writable def put(self, path: str, value: memoryview) -> Written: - return self._put(path, value, None, always) + with self._concurrency.slot(): + 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) + async with self._concurrency.slot(): + 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) + with self._concurrency.slot(): + 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) + async with self._concurrency.slot(): + 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)) + with self._concurrency.slot(): + 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)) + async with self._concurrency.slot(): + 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, @@ -676,67 +711,73 @@ async def _put_async( 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) + with self._concurrency.slot(): + 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) + async with self._concurrency.slot(): + 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) + with self._concurrency.slot(): + 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) + async with self._concurrency.slot(): + 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) - # --- async batches: the async operations, `concurrency` at once + # --- async batches: the async operations, at most `concurrency.limit` started at once def get_many_async( self, requests: Sequence[tuple[str, ByteRange | None]] ) -> AsyncIterator[tuple[int, Found | Missing]]: - return run_many_async(self.get_async, requests, self._concurrency) + return run_many_async(self.get_async, requests, self._concurrency.limit) def get_into_many_async( self, requests: Sequence[tuple[str, Buffer, ByteRange | None]] ) -> AsyncIterator[tuple[int, Copied | Missing]]: - return run_many_async(self.get_into_async, requests, self._concurrency) + return run_many_async(self.get_into_async, requests, self._concurrency.limit) def put_many_async( self, requests: Sequence[tuple[str, memoryview]] ) -> AsyncIterator[tuple[int, Written]]: - return run_many_async(self.put_async, requests, self._concurrency) + return run_many_async(self.put_async, requests, self._concurrency.limit) def delete_many_async( self, paths: Sequence[str] ) -> AsyncIterator[tuple[int, Deleted | Missing]]: - return run_many_async(self.delete_async, [(path,) for path in paths], self._concurrency) + return run_many_async( + self.delete_async, [(path,) for path in paths], self._concurrency.limit + ) # --- Listable diff --git a/packages/zarr-storage/tests/test_batch.py b/packages/zarr-storage/tests/test_batch.py index 40b6b43c9b..c88d7918bc 100644 --- a/packages/zarr-storage/tests/test_batch.py +++ b/packages/zarr-storage/tests/test_batch.py @@ -5,13 +5,13 @@ import asyncio import threading import time -from concurrent.futures import ThreadPoolExecutor from typing import TYPE_CHECKING import pytest from zarr_storage import BatchError from zarr_storage._batch import run_many, run_many_async +from zarr_storage._resources import ThreadPool if TYPE_CHECKING: from collections.abc import AsyncIterator @@ -64,8 +64,11 @@ def _run(tracker: _Tracker, mode: str, window: int, n: int, into: list[tuple[int if mode == "serial": into.extend(run_many(tracker, requests)) elif mode == "threads": - with ThreadPoolExecutor(8) as executor: - into.extend(run_many(tracker, requests, executor, window)) + 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)) diff --git a/packages/zarr-storage/tests/test_local.py b/packages/zarr-storage/tests/test_local.py index a041d7a058..2699181b86 100644 --- a/packages/zarr-storage/tests/test_local.py +++ b/packages/zarr-storage/tests/test_local.py @@ -145,11 +145,6 @@ def test_overlong_key_raises(tmp_path: Path) -> None: Store(LocalBackend(tmp_path)).put("a" * 1000, b"x") -def test_zero_concurrency_raises(tmp_path: Path) -> None: - with pytest.raises(ValueError, match="concurrency"): - LocalBackend(tmp_path, concurrency=0) - - def _create( store: Store[LocalBackend], key: str, barrier: threading.Barrier, results: list[bool] ) -> None: diff --git a/packages/zarr-storage/tests/test_resources.py b/packages/zarr-storage/tests/test_resources.py new file mode 100644 index 0000000000..bf9911bd64 --- /dev/null +++ b/packages/zarr-storage/tests/test_resources.py @@ -0,0 +1,299 @@ +"""Shared resources: thread pools and limiters, alone and as backends use them.""" + +from __future__ import annotations + +import asyncio +import pickle +import threading +import time +from functools import partial +from typing import TYPE_CHECKING + +import pytest +from obstore.store import LocalStore, MemoryStore + +from zarr_storage import Copied, Deleted, Found, Limiter, Missing, Store, ThreadPool +from zarr_storage.backends import LocalBackend, ObjectStoreBackend + +if TYPE_CHECKING: + from collections.abc import Callable + from pathlib import Path + + from zarr_storage import ByteRange + + +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, peak: _Peak) -> None: + with limiter.slot(): + peak.enter() + time.sleep(0.002) + 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() + + +# ---------------------------------------------------------------------------- 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)] + for worker in workers: + worker.start() + for worker in workers: + worker.join() + assert (peak.done, peak.most, limiter.in_use) == (24, limit, 0) + + +async def _nested_async(limiter: Limiter) -> int: + async with limiter.slot(), limiter.slot(): + return limiter.in_use + + +def _nested_sync(limiter: Limiter, seen: list[int]) -> None: + with limiter.slot(), limiter.slot(): + seen.append(limiter.in_use) + seen.append(asyncio.run(_nested_async(limiter))) + + +def test_slot_inside_a_slot_takes_no_second_slot() -> None: + limiter, seen = Limiter(1), [] + assert _finishes(partial(_nested_sync, limiter, seen)) + assert (seen, limiter.in_use) == ([1, 1], 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 + + +@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() + + +class _RecordingBackend(LocalBackend): + """A local backend that records which threads its reads run on.""" + + def __init__(self, root: Path, threads: ThreadPool) -> None: + super().__init__(root, threads=threads) + 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, pool) + store = Store(backend) + keys = [f"k{i}" for i in range(4)] + store.put_many((key, b"x") for key in keys) + try: + worker = pool.submit(_batch_here, store, keys).result(timeout=10) + finally: + pool.shutdown(wait=False) + assert backend.read_on == {worker} + + +@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 test_shutting_down_the_default_pool_raises() -> None: + with pytest.raises(ValueError, match="shared"): + ThreadPool.default().shutdown() + + +# ---------------------------------------------------------------------------- sharing + + +def test_backends_share_resources_as_given(tmp_path: Path) -> None: + """Left out, resources are process-wide defaults; given, they are exactly what was given.""" + assert LocalBackend(tmp_path / "a").threads is ThreadPool.default() + pool = ThreadPool(2) + assert LocalBackend(tmp_path / "b", threads=pool).threads is pool + memory = [ObjectStoreBackend(MemoryStore()).concurrency for _ in range(2)] + local = ObjectStoreBackend(LocalStore(str(tmp_path))).concurrency + assert memory[0] is memory[1] + assert local is not memory[0] + limiter = Limiter(3) + assert ObjectStoreBackend(MemoryStore(), concurrency=limiter).concurrency is limiter + + +def test_pickling_keeps_resources_shared(tmp_path: Path) -> None: + """Backends that shared a resource share one after a round trip; defaults stay defaults.""" + pool, limiter = ThreadPool(2), Limiter(3) + objects = str(tmp_path) # obstore's `MemoryStore` can't be pickled; its `LocalStore` can + backends = ( + LocalBackend(tmp_path / "a", threads=pool), + LocalBackend(tmp_path / "b", threads=pool), + ObjectStoreBackend(LocalStore(objects), concurrency=limiter), + ObjectStoreBackend(LocalStore(objects), concurrency=limiter), + LocalBackend(tmp_path / "c"), + ObjectStoreBackend(LocalStore(objects)), + ) + a, b, c, d, e, f = pickle.loads(pickle.dumps(backends)) + assert a.threads is b.threads + assert a.threads is not pool + assert a.threads.max_workers == 2 + assert c.concurrency is d.concurrency + assert c.concurrency is not limiter + assert c.concurrency.limit == 3 + assert e.threads is ThreadPool.default() + assert f.concurrency is backends[5].concurrency + + +def _get_in_thread(store: Store[ObjectStoreBackend], results: list[object]) -> None: + results.append(store.get("k")) + + +async def _get_async_while_held(store: Store[ObjectStoreBackend]) -> bool: + try: + await asyncio.wait_for(store.as_async().get("k"), 0.05) + except TimeoutError: + return True + return False + + +def test_obstore_operations_wait_for_a_shared_limit() -> None: + """Every operation, sync or async, of every backend sharing a limiter waits for a slot.""" + limiter = Limiter(1) + first = Store(ObjectStoreBackend(MemoryStore(), concurrency=limiter)) + second = Store(ObjectStoreBackend(MemoryStore(), concurrency=limiter)) + second.put("k", b"x") + limiter.acquire() # another backend's operation holds the only slot + results: list[object] = [] + reader = threading.Thread(target=_get_in_thread, args=(second, results)) + reader.start() + reader.join(0.05) + assert reader.is_alive() + assert asyncio.run(_get_async_while_held(first)) + limiter.release() + reader.join(10) + assert isinstance(results[0], Found) + assert limiter.in_use == 0 + + +def _nested_operations(store: Store[ObjectStoreBackend], results: list[object]) -> None: + store.put("k", b"xy") + results.append(store.get_into("k", bytearray(2))) + results.append(store.delete("k")) + + +def test_obstore_operation_that_calls_another_takes_one_slot() -> None: + """`get_into` reads through `get` and `delete` looks with `head`: with one slot, neither waits.""" + store = Store(ObjectStoreBackend(MemoryStore(), concurrency=Limiter(1))) + results: list[object] = [] + assert _finishes(partial(_nested_operations, store, results)) + assert [type(r) for r in results] == [Copied, Deleted] From 9561df2f796ad10c28def9fcc64820dbdfb470e2 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Wed, 18 Nov 2026 11:11:47 +0100 Subject: [PATCH 08/31] docs(zarr-storage): add changelog fragment for shared resources Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-storage/changes/464.feature.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 packages/zarr-storage/changes/464.feature.md diff --git a/packages/zarr-storage/changes/464.feature.md b/packages/zarr-storage/changes/464.feature.md new file mode 100644 index 0000000000..54338b5f7c --- /dev/null +++ b/packages/zarr-storage/changes/464.feature.md @@ -0,0 +1 @@ +Add `ThreadPool` and `Limiter`, resources that `zarr-storage` backends share so their threads and operations in flight are bounded together: `LocalBackend` takes `threads` and `ObjectStoreBackend` takes a `Limiter` as `concurrency`, with process-wide defaults when they are left out. From 61d6d24beb5967da4953928619d7ed53a5942c74 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Wed, 18 Nov 2026 12:00:37 +0100 Subject: [PATCH 09/31] feat(zarr-storage)!: make resource limits part of the store's context Resources move from backends to a Context that every store view carries, as in TensorStore. A Context holds a ThreadPool and a Limiter per resource key, is immutable, and resolves keys through its parents to process-wide defaults. Backends hold no resources: each names the `resource_key` its operations are limited under ("local", "memory", "obstore."), and the store gates every operation with the context's limiter for that key. Store and AsyncStore take `context=`, and gain `with_context` and `limited(n)`, a view whose operations together run at most n at once. `Limiter(n, within=parent)` holds a slot of both, so a scoped limit never escapes the one it narrows (where TensorStore's child contexts replace a resource, this nests). Slots are taken innermost first, and where the work runs: AsyncStore runs a sync-only backend on the context's thread pool and takes the slot on the pool thread, so no operation holds a slot while it waits for a thread. LocalBackend is now sync-only; AsyncStore adapts it. Batches run single operations concurrently under the context (a Store batch on the pool, an AsyncStore batch as tasks, up to the limiter's limit), which also makes sync obstore batches concurrent. Native batch methods receive the context. Slots are no longer re-entrant: re-entrancy through a context variable leaked into tasks and, on free-threaded 3.14, into new threads, letting a fan-out run unbounded under one slot. BREAKING CHANGE: LocalBackend's `threads`, its async methods and ObjectStoreBackend's `concurrency` are gone; pass resources in a Context. Backends must provide `resource_key`. Batch protocol methods take the context. Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-storage/DESIGN.md | 126 +++-- packages/zarr-storage/changes/464.feature.md | 2 +- .../zarr-storage/src/zarr_storage/__init__.py | 7 +- .../src/zarr_storage/_protocols.py | 60 +- .../src/zarr_storage/_resources.py | 295 +++++++--- .../zarr-storage/src/zarr_storage/_store.py | 516 +++++++++++++----- .../src/zarr_storage/backends/_local.py | 140 +---- .../src/zarr_storage/backends/_memory.py | 4 + .../src/zarr_storage/backends/_obstore.py | 301 ++++------ .../src/zarr_storage/testing/_api.py | 14 +- packages/zarr-storage/tests/test_resources.py | 354 ++++++++---- packages/zarr-storage/tests/test_store.py | 31 +- 12 files changed, 1120 insertions(+), 730 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 62ace954e5..002192178b 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -27,8 +27,9 @@ Sources, and what each contributed: ``` Backend capability protocols over backend paths; owns shared state and lifecycle ▲ -_View (backend, root, read_only, owner): validates keys, applies the root, relativizes - ▲ listings, enforces read-only; `store / "a"` is a view on the same backend +_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()` ``` @@ -37,18 +38,22 @@ A **backend** is an object that implements some capability protocols (`Readable` `Listable`, `WritableIfMatch`, `DeletableIfMatch`, and their async twins) on *backend paths*: `/`-separated strings, already joined with the root. 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. Thread pools and limits on operations in flight are shared -resources the backend is given (see below). +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. All key validation, root joining, listing relativization and read-only enforcement 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, +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, 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 with both surfaces serves both; `store.as_async()` and `astore.as_sync()` are +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. @@ -123,13 +128,16 @@ landed with their results and whose `remaining` holds the requests that failed o (`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 the single -operation one at a time; a backend that has a batch capability (`ReadableMany`, -`ReadableIntoMany[O]`, `WritableMany`, and async twins) is used instead. The rule for such -fallbacks: `Store` may fall back when only speed differs, never when behavior does. A serial batch -returns what a concurrent one 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. The batch runners in -`zarr_storage._batch` implement the windowing and failure rule once, for `Store` and backends alike. +`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. The batch +runners in `zarr_storage._batch` implement the windowing and failure rule once. Listing arguments are checked when the method is called; the items are produced lazily, and taking one after the store closes raises `StoreClosedError`. @@ -143,8 +151,9 @@ raises `InvalidByteRangeError`; a suffix longer than the value returns the whole ## Views, lifecycle, identity -- `store / "a"`, `store.with_read_only(True)` and `store.as_async()` (or `as_sync()`) return views - on the same backend. A view of a +- `store / "a"`, `store.with_read_only(True)`, `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. A view of a read-only store is read-only; `with_read_only(False)` on one raises `ReadOnlyError`. - The store the user constructed owns the backend. `close()` (`aclose()` on an `AsyncStore`) on it closes the backend; on a derived view it does nothing. After the backend closes, every view raises `StoreClosedError`. @@ -168,12 +177,10 @@ key (`a/b` when `a` is a key): that reads as absent. | `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` runs its async operations -and its batches, sync and async, on its `threads`, as many batch operations at once as the pool has -threads. `ObjectStoreBackend` holds a slot of its `concurrency` limiter for every operation, sync -and async, single and batched; async batches start at most `concurrency.limit` operations at once, -and sync batches run one at a time. `MemoryBackend` uses `Store`'s serial batches, which are as fast -for it. +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 @@ -214,47 +221,60 @@ step, each stored key reads back as the model says, through `get` and `get_many` `get_if_changed` with its generation is `Unchanged`. The obstore tests also fail any async run that makes a blocking obstore call. -## Shared resources - -Threads and limits on operations in flight are resources that backends share, after TensorStore's -context resources (`file_io_concurrency`, `s3_request_concurrency`). zarrs has no I/O limits of its -own (its `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. - -- `ThreadPool(max_workers)` runs blocking work: `LocalBackend(root, threads=...)`. -- `Limiter(limit)` caps operations in flight, for threads and tasks on any event loop in one - first-come, first-served queue: `ObjectStoreBackend(store, concurrency=...)`. `limiter.slot()` is - a sync or async context manager. A slot is held for a whole operation, and an operation that calls - another through a limiter it already holds takes no second slot (a context variable records the - slots an operation holds), so `get_into`, which reads through `get`, can't wait on itself. -- Pass one resource to several backends to bound them together. Left out, a backend uses a - process-wide default, as TensorStore does: `ThreadPool.default()` of `max(4, cpu_count)` threads, - and one `Limiter(32)` per obstore store class, so every S3 backend in a process shares one limit - and an HTTP backend doesn't share it. A default is shared state, but it changes only speed, never - what an operation does; pass your own resource to isolate a backend. -- Whoever creates a resource owns it: a backend never shuts down a pool it was given, and closing a - `LocalBackend` refuses new operations without stopping the pool. The default pool can't be shut - down. -- Pickling a resource pickles its settings, and pickle stores each object once, so backends that - shared a resource share one new resource after a round trip; a default unpickles as the receiving - process's default. +## 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 through the view 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`. 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. +- `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: waiting there for work queued on the same pool could wait forever once every thread does it. -- Thread 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. +- 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. ## Configuration No global configuration. Every knob is a constructor parameter with its default in the signature; -the shared resources above are passed the same way. +resources are passed in a store's context. ## 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. -- Sync batches over obstore run one request at a time; a thread pool, or a native batch call, - would overlap them. +- Listings hold no slot of the context's limiter. - `get_ranges_into`, `put_from`, and a GPU direct storage backend whose `get_into_many` submits one cuFile batch. diff --git a/packages/zarr-storage/changes/464.feature.md b/packages/zarr-storage/changes/464.feature.md index 54338b5f7c..20d405e110 100644 --- a/packages/zarr-storage/changes/464.feature.md +++ b/packages/zarr-storage/changes/464.feature.md @@ -1 +1 @@ -Add `ThreadPool` and `Limiter`, resources that `zarr-storage` backends share so their threads and operations in flight are bounded together: `LocalBackend` takes `threads` and `ObjectStoreBackend` takes a `Limiter` as `concurrency`, with process-wide defaults when they are left out. +Add `Context`, the resources a `zarr-storage` store's operations draw on: a `ThreadPool` and a `Limiter` per backend resource key, with process-wide defaults. Every store view carries a context (`Store(backend, context=...)`, `with_context`), stores sharing a context share its limits, and `store.limited(n)` bounds a burst of operations within the context's limit. `AsyncStore` now runs a sync-only backend on the context's thread pool, and batches run concurrently under the context. diff --git a/packages/zarr-storage/src/zarr_storage/__init__.py b/packages/zarr-storage/src/zarr_storage/__init__.py index d18fb9ee4a..c5ac6b8a9a 100644 --- a/packages/zarr-storage/src/zarr_storage/__init__.py +++ b/packages/zarr-storage/src/zarr_storage/__init__.py @@ -3,8 +3,8 @@ 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, and are the only -objects most callers need. +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. """ from zarr_storage._errors import ( @@ -39,7 +39,7 @@ WritableMany, WritableManyAsync, ) -from zarr_storage._resources import Limiter, ThreadPool +from zarr_storage._resources import Context, Limiter, ThreadPool from zarr_storage._store import AsyncStore, Store from zarr_storage._types import ( ByteRange, @@ -68,6 +68,7 @@ "BatchError", "ByteRange", "ClosableAsync", + "Context", "Copied", "DeletableIfMatch", "DeletableIfMatchAsync", diff --git a/packages/zarr-storage/src/zarr_storage/_protocols.py b/packages/zarr-storage/src/zarr_storage/_protocols.py index 7058b87ca7..dd06555970 100644 --- a/packages/zarr-storage/src/zarr_storage/_protocols.py +++ b/packages/zarr-storage/src/zarr_storage/_protocols.py @@ -8,15 +8,22 @@ `/`. 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 and `AsyncStore` the async ones, and -their 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`. +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 optional and change only speed: `Store.get_many` and its siblings work on any backend that -can read or write, one operation at a time, and use a backend's batch methods when it has them. A -batch method yields `(index, result)` pairs as operations finish and follows the failure rule of -`zarr_storage._batch`, whose runners implement it. +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._batch`. """ from __future__ import annotations @@ -26,6 +33,7 @@ if TYPE_CHECKING: from collections.abc import AsyncIterator, Iterator, Sequence + from zarr_storage._resources import Context from zarr_storage._types import ( ByteRange, Copied, @@ -70,7 +78,17 @@ class Backend(Protocol): - """What every backend provides: a lifecycle and whether it accepts writes at all.""" + """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 closed(self) -> bool: @@ -171,7 +189,7 @@ def delete_if_match(self, path: str, generation: Generation) -> Deleted | Reject @runtime_checkable class ReadableMany(Backend, Protocol): def get_many( - self, requests: Sequence[tuple[str, ByteRange | None]] + 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.""" ... @@ -180,7 +198,7 @@ def get_many( @runtime_checkable class ReadableIntoMany(Backend, Protocol[O_contra]): def get_into_many( - self, requests: Sequence[tuple[str, O_contra, ByteRange | None]] + 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)`.""" ... @@ -188,11 +206,15 @@ def get_into_many( @runtime_checkable class WritableMany(Backend, Protocol): - def put_many(self, requests: Sequence[tuple[str, memoryview]]) -> Iterator[tuple[int, Written]]: + 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]) -> Iterator[tuple[int, Deleted | Missing]]: + def delete_many( + self, paths: Sequence[str], context: Context + ) -> Iterator[tuple[int, Deleted | Missing]]: """`delete` for each path, yielding `(index, result)` as each finishes.""" ... @@ -207,6 +229,7 @@ def list_dir(self, directory: str) -> Iterator[ListItem]: ... +@runtime_checkable class ReadableAsync(Backend, Protocol): async def get_async(self, path: str, byte_range: ByteRange | None) -> Found | Missing: ... @@ -221,12 +244,14 @@ async def get_ranges_async( async def head_async(self, path: str) -> ObjectMetadata | Missing: ... +@runtime_checkable class ReadableIntoAsync(Backend, Protocol[O_contra]): async def get_into_async( self, path: str, out: O_contra, byte_range: ByteRange | None ) -> Copied | Missing: ... +@runtime_checkable class WritableAsync(Backend, Protocol): async def put_async(self, path: str, value: memoryview) -> Written: ... @@ -237,12 +262,14 @@ async def delete_async(self, path: str) -> Deleted | Missing: ... async def delete_dir_async(self, directory: str) -> None: ... +@runtime_checkable class WritableIfMatchAsync(Backend, Protocol): async def put_if_match_async( self, path: str, value: memoryview, generation: Generation ) -> Written | Rejected | Missing: ... +@runtime_checkable class DeletableIfMatchAsync(Backend, Protocol): async def delete_if_match_async( self, path: str, generation: Generation @@ -252,28 +279,29 @@ async def delete_if_match_async( @runtime_checkable class ReadableManyAsync(Backend, Protocol): def get_many_async( - self, requests: Sequence[tuple[str, ByteRange | None]] + self, requests: Sequence[tuple[str, ByteRange | None]], context: Context ) -> AsyncIterator[tuple[int, Found | Missing]]: ... @runtime_checkable class ReadableIntoManyAsync(Backend, Protocol[O_contra]): def get_into_many_async( - self, requests: Sequence[tuple[str, O_contra, ByteRange | None]] + self, requests: Sequence[tuple[str, O_contra, ByteRange | None]], context: Context ) -> AsyncIterator[tuple[int, Copied | Missing]]: ... @runtime_checkable class WritableManyAsync(Backend, Protocol): def put_many_async( - self, requests: Sequence[tuple[str, memoryview]] + self, requests: Sequence[tuple[str, memoryview]], context: Context ) -> AsyncIterator[tuple[int, Written]]: ... def delete_many_async( - self, paths: Sequence[str] + self, paths: Sequence[str], context: Context ) -> AsyncIterator[tuple[int, Deleted | Missing]]: ... +@runtime_checkable class ListableAsync(Backend, Protocol): def list_async(self, directory: str) -> AsyncIterator[str]: ... diff --git a/packages/zarr-storage/src/zarr_storage/_resources.py b/packages/zarr-storage/src/zarr_storage/_resources.py index 5f4671e01b..ca9c9e8ec5 100644 --- a/packages/zarr-storage/src/zarr_storage/_resources.py +++ b/packages/zarr-storage/src/zarr_storage/_resources.py @@ -1,35 +1,46 @@ -"""Resources that backends share: thread pools and limits on operations in flight. - -Modeled on TensorStore's context resources (`file_io_concurrency`, `s3_request_concurrency`): a -resource is an object you create and pass to as many backends as should share it. A backend never -closes a resource it was given. Left out, a backend uses a process-wide default, as TensorStore -does, because threads and request slots are process-wide in the end; pass your own to isolate a -backend from the rest of the process. A resource changes how fast operations run, never what they -do. - -Pickling a resource pickles its settings. Pickle stores each object once, so backends that shared -a resource before pickling share one new resource after; a default resource unpickles as the -default of the receiving process. +"""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 contextvars import ContextVar from functools import partial +from types import MappingProxyType from typing import TYPE_CHECKING, Final, TypeVar, TypeVarTuple if TYPE_CHECKING: - from collections.abc import Callable + from collections.abc import Callable, Mapping from concurrent.futures import Future - from contextvars import Token from types import TracebackType -__all__ = ["Limiter", "Slot", "ThreadPool", "default_limiter", "default_thread_pool"] +__all__ = [ + "Context", + "Limiter", + "Slot", + "ThreadPool", + "default_context", + "default_limiter", + "default_thread_pool", +] R = TypeVar("R") Ts = TypeVarTuple("Ts") @@ -59,10 +70,11 @@ def _mark_worker(pool: ThreadPool) -> None: class ThreadPool: - """Threads that run blocking operations, such as file I/O, for the backends given it. + """Threads that run blocking operations, such as file I/O. - The threads start when first needed. Whoever creates a pool owns it and may `shutdown` it once - no backend needs it; the default pool lives as long as the process. + 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 ---------- @@ -78,7 +90,7 @@ def __init__(self, max_workers: int) -> None: @classmethod def default(cls) -> ThreadPool: - """The process-wide pool that backends use when given none.""" + """The process-wide pool, of `DEFAULT_THREADS` threads.""" return default_thread_pool() @property @@ -106,18 +118,20 @@ 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; the batch runners run such work inline. + 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.""" - return self._pool().submit(fn, *args) + 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.""" + context = contextvars.copy_context() loop = asyncio.get_running_loop() - return await loop.run_in_executor(self._pool(), partial(fn, *args)) + 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. @@ -141,13 +155,13 @@ def shutdown(self, *, wait: bool = True) -> None: raise ValueError("The default thread pool is shared by the whole process.") -_default_pool_lock = threading.Lock() +_defaults_lock = threading.Lock() _default_pool: list[ThreadPool] = [] def default_thread_pool() -> ThreadPool: - """The process-wide `ThreadPool`, with `DEFAULT_THREADS` threads.""" - with _default_pool_lock: + """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] @@ -155,11 +169,6 @@ def default_thread_pool() -> ThreadPool: # ---------------------------------------------------------------------------- limiters -_held: ContextVar[frozenset[Limiter]] = ContextVar( - "zarr_storage_held_limiters", default=frozenset() -) -"""The limiters whose slots the current operation holds, so nested operations don't wait again.""" - class _ThreadWaiter: """A thread blocked on a limiter.""" @@ -200,20 +209,29 @@ def grant(self) -> bool: 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, across every backend given it. + """A limit on how many operations run at once. - Threads and tasks on any event loop wait in one first-come, first-served queue. + 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) -> None: + 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() @@ -222,6 +240,11 @@ def __init__(self, limit: int) -> None: 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.""" @@ -231,14 +254,25 @@ 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,)) + 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`), that holds one slot. + """A context manager, sync (`with`) or async (`async with`), holding a slot of this limiter + and of each limiter it lies within. - Prefer it to `acquire` and `release`: it releases on error, and inside an operation that - already holds a slot of this limiter it takes no second one, so an operation that calls - another can't wait on itself. + 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) @@ -250,7 +284,7 @@ def _take(self) -> bool: return False def acquire(self) -> None: - """Take a slot, blocking the calling thread until one is free.""" + """Take a slot of this limiter alone, blocking the calling thread until one is free.""" with self._lock: if self._take(): return @@ -259,7 +293,7 @@ def acquire(self) -> None: waiter.wait() async def acquire_async(self) -> None: - """Take a slot, waiting without blocking the event loop until one is free.""" + """Take a slot of this limiter alone, waiting without blocking the event loop.""" with self._lock: if self._take(): return @@ -278,7 +312,7 @@ async def acquire_async(self) -> None: raise def release(self) -> None: - """Give back a slot, to the longest waiter if there is one. + """Give back a slot of this limiter, to the longest waiter if there is one. Raises `RuntimeError` if no slot is held. """ @@ -291,32 +325,31 @@ def release(self) -> None: self._in_use -= 1 -class Slot: - """One use of a `Limiter`: holds a slot from entry to exit, unless the operation holds one.""" +def _release_all(limiters: list[Limiter]) -> None: + for limiter in reversed(limiters): + limiter.release() - __slots__ = ("_limiter", "_token") - def __init__(self, limiter: Limiter) -> None: - self._limiter = limiter - self._token: Token[frozenset[Limiter]] | None = None - - def _needed(self) -> bool: - return self._limiter not in _held.get() +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.""" - def _mark(self) -> None: - self._token = _held.set(_held.get() | {self._limiter}) + __slots__ = ("_chain", "_taken") - def _unmark(self) -> None: - if self._token is None: - return - _held.reset(self._token) - self._token = None - self._limiter.release() + def __init__(self, limiter: Limiter) -> None: + self._chain = limiter.chain() + self._taken: list[Limiter] = [] def __enter__(self) -> None: - if self._needed(): - self._limiter.acquire() - self._mark() + 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, @@ -324,12 +357,19 @@ def __exit__( exc: BaseException | None, tb: TracebackType | None, ) -> None: - self._unmark() + taken, self._taken = self._taken, [] + _release_all(taken) async def __aenter__(self) -> None: - if self._needed(): - await self._limiter.acquire_async() - self._mark() + 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, @@ -337,7 +377,8 @@ async def __aexit__( exc: BaseException | None, tb: TracebackType | None, ) -> None: - self._unmark() + taken, self._taken = self._taken, [] + _release_all(taken) class _DefaultLimiter(Limiter): @@ -351,14 +392,128 @@ def __reduce__(self) -> tuple[object, ...]: return (default_limiter, (self._key,)) -_default_limiters_lock = threading.Lock() _default_limiters: dict[str, Limiter] = {} def default_limiter(key: str) -> Limiter: - """The process-wide `Limiter` for `key` (such as an obstore store class), of `DEFAULT_LIMIT`.""" - with _default_limiters_lock: + """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/_store.py b/packages/zarr-storage/src/zarr_storage/_store.py index de7dedc71b..6d443a84bb 100644 --- a/packages/zarr-storage/src/zarr_storage/_store.py +++ b/packages/zarr-storage/src/zarr_storage/_store.py @@ -1,13 +1,21 @@ -"""`Store` and `AsyncStore`: views of a backend at a root, through sync methods or coroutines. +"""`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. +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. """ from __future__ import annotations from collections.abc import AsyncGenerator, Generator -from typing import TYPE_CHECKING, Final, Generic, Self, TypeVar, cast, final +from typing import TYPE_CHECKING, Final, Generic, Self, TypeVar, TypeVarTuple, cast, final from zarr_storage._batch import run_many, run_many_async from zarr_storage._buffers import byte_view @@ -16,35 +24,37 @@ from zarr_storage._protocols import ( Backend, ClosableAsync, + DeletableIfMatchAsync, + ListableAsync, + ReadableAsync, + ReadableIntoAsync, ReadableIntoMany, ReadableIntoManyAsync, ReadableMany, ReadableManyAsync, + WritableAsync, + WritableIfMatchAsync, WritableMany, WritableManyAsync, ) +from zarr_storage._resources import default_context from zarr_storage._types import Missing if TYPE_CHECKING: - from collections.abc import AsyncIterator, Iterable, Iterator, Sequence + from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Sequence from types import TracebackType from typing_extensions import Buffer from zarr_storage._protocols import ( DeletableIfMatch, - DeletableIfMatchAsync, Listable, - ListableAsync, Readable, - ReadableAsync, ReadableInto, - ReadableIntoAsync, Writable, - WritableAsync, WritableIfMatch, - WritableIfMatchAsync, ) + from zarr_storage._resources import Context, Limiter, Slot from zarr_storage._types import ( ByteRange, Copied, @@ -65,19 +75,40 @@ 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.""" +def _limited(limiter: Limiter, fn: Callable[[*Ts], R], *args: *Ts) -> R: + """`fn(*args)`, holding a slot of `limiter`, on the calling thread.""" + with limiter.slot(): + 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, ownership.""" + """What `Store` and `AsyncStore` share: a backend, a root, read-only access, a context, and + ownership.""" - __slots__ = ("_backend", "_owner", "_read_only", "_root") + __slots__ = ("_backend", "_context", "_limiter", "_owner", "_read_only", "_root") - def __init__(self, backend: B_co, *, root: str = "", read_only: bool = False) -> None: + def __init__( + self, + backend: B_co, + *, + root: str = "", + read_only: bool = False, + context: Context | None = None, + ) -> None: self._backend: Final[B_co] = backend self._root: Final[str] = normalize_directory(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 = True # ----------------------------------------------------------------- views and identity @@ -97,20 +128,27 @@ 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 - def _view(self, *, root: str, read_only: bool) -> Self: - view = type(self)(self._backend, root=root, read_only=read_only) + def _view(self, *, root: str, read_only: bool, context: Context) -> Self: + view = type(self)(self._backend, root=root, read_only=read_only, context=context) view._owner = False return view 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 + root=join(self._root, normalize_directory(directory)), + read_only=self._read_only, + context=self._context, ) def with_read_only(self, read_only: bool = True) -> Self: @@ -121,7 +159,19 @@ def with_read_only(self, read_only: bool = True) -> Self: """ if self._read_only and not read_only: raise ReadOnlyError(f"{self!r} is read-only; its views are read-only too.") - return self._view(root=self._root, read_only=read_only) + return self._view(root=self._root, read_only=read_only, 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: _View[Backend]) -> bool: """Whether `other` reads and writes through the same backend object.""" @@ -138,7 +188,10 @@ def __repr__(self) -> str: return f"{type(self).__name__}({self._backend!r}, root={self._root!r}{flags})" def __reduce__(self) -> tuple[object, ...]: - return (_restore_store, (type(self), self._backend, self._root, self._read_only)) + return ( + _restore_store, + (type(self), self._backend, self._root, self._read_only, self._context), + ) # ----------------------------------------------------------------- path handling @@ -154,16 +207,8 @@ def _directory(self, directory: str) -> str: self._check_open() return join(self._root, normalize_directory(directory)) - 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 - - async def _open_items_async(self, items: AsyncIterator[T]) -> AsyncIterator[T]: - async for item in items: - self._check_open() - yield item + def _slot(self) -> Slot: + return self._limiter.slot() def _writable_path(self, key: str) -> str: path = self._path(key) @@ -207,20 +252,33 @@ def _writable_paths(self, keys: Sequence[str]) -> list[str]: seen.add(path) 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, through sync methods. + """A backend seen from a root directory, under a context, through sync methods. Construct a store from a backend; the store you construct owns the backend and closes it. - `store / "a"`, `with_read_only()` 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. + `store / "a"`, `with_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. - `backend` gives direct access to the backend, which bypasses the key grammar, the root, and - read-only and closed checks. + 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. Stores have no value equality: `==` is identity. Use `shares_backend` and `overlaps` to compare stores. @@ -234,16 +292,27 @@ class Store(_View[B_co]): 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, *, root: str = "", read_only: bool = False) -> None: - super().__init__(backend, root=root, read_only=read_only) + def __init__( + self, + backend: B_co, + *, + root: str = "", + read_only: bool = False, + context: Context | None = None, + ) -> None: + super().__init__(backend, root=root, read_only=read_only, context=context) def as_async(self) -> AsyncStore[B_co]: - """An `AsyncStore` view on the same backend and root; it doesn't own the backend.""" - view = AsyncStore(self._backend, root=self._root, read_only=self._read_only) + """An `AsyncStore` view on the same backend, root and context; it doesn't own the backend.""" + view = AsyncStore( + self._backend, root=self._root, read_only=self._read_only, context=self._context + ) view._owner = False return view @@ -265,7 +334,13 @@ def __exit__( ) -> None: self.close() - # ----------------------------------------------------------------- batch results + # ----------------------------------------------------------------- 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]] @@ -299,13 +374,33 @@ def _finished(batch: Sequence[T], results: Iterator[tuple[int, R]]) -> list[tupl 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._backend.get(self._path(key), byte_range) + return self._get(self._path(key), byte_range) def get_if_changed( self: Store[Readable], @@ -318,13 +413,17 @@ def get_if_changed( This revalidates a cached copy, as an HTTP `If-None-Match` request does. """ - return self._backend.get_if_changed(self._path(key), generation, byte_range) + 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.""" - return self._backend.get_ranges(self._path(key), ranges) + 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 @@ -335,11 +434,13 @@ def get_into( 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._backend.get_into(self._path(key), out, byte_range) + 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`.""" - return self._backend.head(self._path(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.""" @@ -349,13 +450,14 @@ def exists(self: Store[Readable], key: str) -> bool: def put(self: Store[Writable], key: str, value: Buffer) -> Written: """Write `value` at `key`.""" - return self._backend.put(self._writable_path(key), byte_view(value, writable=False)) + 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.""" - return self._backend.put_if_absent( - self._writable_path(key), byte_view(value, writable=False) - ) + 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 @@ -364,23 +466,28 @@ def put_if_match( `Rejected` if the key holds another generation, `Missing` if it holds no value. """ - return self._backend.put_if_match( - self._writable_path(key), byte_view(value, writable=False), generation - ) + 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._backend.delete(self._writable_path(key)) + 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`.""" - return self._backend.delete_if_match(self._writable_path(key), 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).""" - self._backend.delete_dir(self._writable_directory(directory)) + path = self._writable_directory(directory) + with self._slot(): + self._backend.delete_dir(path) # ----------------------------------------------------------------- batches @@ -391,9 +498,10 @@ def get_many( 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 happen as the pairs are taken, 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). + 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 @@ -404,8 +512,8 @@ def get_many( paths = [self._read_request(request) for request in batch] backend = self._backend if isinstance(backend, ReadableMany): - return self._streamed(batch, backend.get_many(paths)) - return self._streamed(batch, run_many(backend.get, paths)) + 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]], @@ -421,8 +529,8 @@ def get_into_many( backend = self._backend if isinstance(backend, ReadableIntoMany): many = cast("ReadableIntoMany[O]", backend) - return self._streamed(batch, many.get_into_many(paths)) - return self._streamed(batch, run_many(backend.get_into, paths)) + 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]] @@ -434,17 +542,11 @@ def put_many( finish, no others start, and `BatchError` reports the keys written (`completed`, with their results) and the rest (`remaining`). """ - batch = list(items) - keys = [key for key, _ in batch] - paths = self._writable_paths(keys) - requests = [ - (path, byte_view(value, writable=False)) - for path, (_, value) in zip(paths, batch, strict=True) - ] + keys, requests = self._put_requests(items) backend = self._backend if isinstance(backend, WritableMany): - return self._finished(keys, backend.put_many(requests)) - return self._finished(keys, run_many(backend.put, requests)) + 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] @@ -454,16 +556,22 @@ def delete_many( paths = self._writable_paths(batch) backend = self._backend if isinstance(backend, WritableMany): - return self._finished(batch, backend.delete_many(paths)) - return self._finished(batch, run_many(backend.delete, [(path,) for path in paths])) + 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`. + `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) @@ -479,12 +587,13 @@ def list_dir(self: Store[Listable], directory: str = "") -> Iterator[ListItem]: @final class AsyncStore(_View[B_co]): - """A backend seen from a root directory, through coroutines. + """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, over the - backend's async capabilities (`ReadableAsync`, `WritableAsync`, ...). Listings and lazy batches - are async iterators. Construct one from a backend, or take `store.as_async()`; `as_sync()` - goes back. Close it with `await store.aclose()` or `async with`. + 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 from a backend, or take `store.as_async()`; `as_sync()` goes back. + Close it with `await store.aclose()` or `async with`. Parameters ---------- @@ -495,16 +604,27 @@ class AsyncStore(_View[B_co]): 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, *, root: str = "", read_only: bool = False) -> None: - super().__init__(backend, root=root, read_only=read_only) + def __init__( + self, + backend: B_co, + *, + root: str = "", + read_only: bool = False, + context: Context | None = None, + ) -> None: + super().__init__(backend, root=root, read_only=read_only, context=context) def as_sync(self) -> Store[B_co]: - """A `Store` view on the same backend and root; it doesn't own the backend.""" - view = Store(self._backend, root=self._root, read_only=self._read_only) + """A `Store` view on the same backend, root and context; it doesn't own the backend.""" + view = Store( + self._backend, root=self._root, read_only=self._read_only, context=self._context + ) view._owner = False return view @@ -534,7 +654,11 @@ async def __aexit__( ) -> None: await self.aclose() - # ----------------------------------------------------------------- batch results + # ----------------------------------------------------------------- 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.""" + return await self._context.threads.run(_limited, self._limiter, fn, *args) async def _streamed( self, batch: Sequence[T], results: AsyncIterator[tuple[int, R]] @@ -567,102 +691,195 @@ async def _finished( 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], key: str, *, byte_range: ByteRange | None = None + self: AsyncStore[ReadableAsync] | AsyncStore[Readable], + key: str, + *, + byte_range: ByteRange | None = None, ) -> Found | Missing: """As `Store.get`.""" - return await self._backend.get_async(self._path(key), byte_range) + return await self._get(self._path(key), byte_range) async def get_if_changed( - self: AsyncStore[ReadableAsync], + self: AsyncStore[ReadableAsync] | AsyncStore[Readable], key: str, generation: Generation, *, byte_range: ByteRange | None = None, ) -> Found | Missing | Unchanged: """As `Store.get_if_changed`.""" - return await self._backend.get_if_changed_async(self._path(key), generation, byte_range) + 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], key: str, ranges: Sequence[ByteRange] + self: AsyncStore[ReadableAsync] | AsyncStore[Readable], + key: str, + ranges: Sequence[ByteRange], ) -> FoundRanges | Missing: """As `Store.get_ranges`.""" - return await self._backend.get_ranges_async(self._path(key), 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]], + 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._backend.get_into_async(self._path(key), out, byte_range) + return await self._get_into(self._path(key), out, byte_range) - async def head(self: AsyncStore[ReadableAsync], key: str) -> ObjectMetadata | Missing: + async def head( + self: AsyncStore[ReadableAsync] | AsyncStore[Readable], key: str + ) -> ObjectMetadata | Missing: """As `Store.head`.""" - return await self._backend.head_async(self._path(key)) + 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], key: str) -> bool: + 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], key: str, value: Buffer) -> Written: + async def put( + self: AsyncStore[WritableAsync] | AsyncStore[Writable], key: str, value: Buffer + ) -> Written: """As `Store.put`.""" - return await self._backend.put_async( - self._writable_path(key), byte_view(value, writable=False) - ) + return await self._put(self._writable_path(key), byte_view(value, writable=False)) async def put_if_absent( - self: AsyncStore[WritableAsync], key: str, value: Buffer + self: AsyncStore[WritableAsync] | AsyncStore[Writable], key: str, value: Buffer ) -> Written | Rejected: """As `Store.put_if_absent`.""" - return await self._backend.put_if_absent_async( - self._writable_path(key), byte_view(value, writable=False) - ) + 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], key: str, value: Buffer, generation: Generation + self: AsyncStore[WritableIfMatchAsync] | AsyncStore[WritableIfMatch], + key: str, + value: Buffer, + generation: Generation, ) -> Written | Rejected | Missing: """As `Store.put_if_match`.""" - return await self._backend.put_if_match_async( - self._writable_path(key), byte_view(value, writable=False), generation - ) - - async def delete(self: AsyncStore[WritableAsync], key: str) -> Deleted | Missing: + 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._backend.delete_async(self._writable_path(key)) + return await self._delete(self._writable_path(key)) async def delete_if_match( - self: AsyncStore[DeletableIfMatchAsync], key: str, generation: Generation + self: AsyncStore[DeletableIfMatchAsync] | AsyncStore[DeletableIfMatch], + key: str, + generation: Generation, ) -> Deleted | Rejected | Missing: """As `Store.delete_if_match`.""" - return await self._backend.delete_if_match_async(self._writable_path(key), generation) + 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], directory: str = "") -> None: + async def delete_dir( + self: AsyncStore[WritableAsync] | AsyncStore[Writable], directory: str = "" + ) -> None: """As `Store.delete_dir`.""" - await self._backend.delete_dir_async(self._writable_directory(directory)) + 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], requests: Iterable[Q] + self: AsyncStore[ReadableAsync] | AsyncStore[Readable], requests: Iterable[Q] ) -> AsyncIterator[tuple[Q, Found | Missing]]: - """As `Store.get_many`.""" + """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)) - return self._streamed(batch, run_many_async(backend.get_async, paths)) + 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]], + 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`.""" @@ -672,48 +889,69 @@ def get_into_many( backend = self._backend if isinstance(backend, ReadableIntoManyAsync): many = cast("ReadableIntoManyAsync[O]", backend) - return self._streamed(batch, many.get_into_many_async(paths)) - return self._streamed(batch, run_many_async(backend.get_into_async, paths)) + 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], items: Iterable[tuple[str, Buffer]] + self: AsyncStore[WritableAsync] | AsyncStore[Writable], + items: Iterable[tuple[str, Buffer]], ) -> list[tuple[str, Written]]: """As `Store.put_many`.""" - batch = list(items) - keys = [key for key, _ in batch] - paths = self._writable_paths(keys) - requests = [ - (path, byte_view(value, writable=False)) - for path, (_, value) in zip(paths, batch, strict=True) - ] + keys, requests = self._put_requests(items) backend = self._backend if isinstance(backend, WritableManyAsync): - return await self._finished(keys, backend.put_many_async(requests)) - return await self._finished(keys, run_many_async(backend.put_async, requests)) + 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], keys: Iterable[str] + 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)) + 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(backend.delete_async, [(path,) for path in paths]) + batch, run_many_async(self._delete, requests, self._limiter.limit) ) # ----------------------------------------------------------------- listing - def list(self: AsyncStore[ListableAsync], directory: str = "") -> AsyncIterator[str]: + 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`.""" - paths = self._backend.list_async(self._directory(directory)) - return self._open_items_async(_relativized(paths, self._root)) + 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], directory: str = "") -> AsyncIterator[ListItem]: + def list_dir( + self: AsyncStore[ListableAsync] | AsyncStore[Listable], directory: str = "" + ) -> AsyncIterator[ListItem]: """As `Store.list_dir`.""" - return self._open_items_async(self._backend.list_dir_async(self._directory(directory))) + 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( @@ -737,6 +975,6 @@ async def _relativized(paths: AsyncIterator[str], root: str) -> AsyncIterator[st def _restore_store( - cls: type[_View[Backend]], backend: Backend, root: str, read_only: bool + cls: type[_View[Backend]], backend: Backend, root: str, read_only: bool, context: Context ) -> _View[Backend]: - return cls(backend, root=root, read_only=read_only) + return cls(backend, root=root, read_only=read_only, context=context) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index 5545ce5f02..9521876845 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -12,18 +12,15 @@ import time import uuid from pathlib import Path -from typing import TYPE_CHECKING, TypedDict, TypeVar, TypeVarTuple +from typing import TYPE_CHECKING, TypedDict, TypeVar -from zarr_storage._batch import run_many, run_many_async from zarr_storage._buffers import byte_view from zarr_storage._byte_range import resolve from zarr_storage._errors import ( InvalidKeyError, KeyConflictError, - StoreClosedError, UnsupportedOperationError, ) -from zarr_storage._resources import ThreadPool, default_thread_pool from zarr_storage._types import ( Copied, Deleted, @@ -40,7 +37,7 @@ from zarr_storage.backends._common import IfMatch, always, if_absent if TYPE_CHECKING: - from collections.abc import AsyncIterator, Callable, Generator, Iterator, Sequence + from collections.abc import Callable, Generator, Iterator, Sequence from io import BufferedReader from typing_extensions import Buffer @@ -71,14 +68,12 @@ ) _WINDOWS_FORBIDDEN_CHARACTERS = frozenset('<>:"\\|?*') | frozenset(chr(i) for i in range(32)) -Ts = TypeVarTuple("Ts") R = TypeVar("R") T = TypeVar("T") class _State(TypedDict): root: str - threads: ThreadPool closed: bool @@ -394,11 +389,6 @@ class LocalBackend: create Create `root` if it doesn't exist. With `create=False`, a missing root raises `FileNotFoundError`. - threads - The threads that run the async methods' file operations and the operations of batches - (`get_many`, `put_many`, ...), which run as many at once as the pool has threads. Share one - pool between backends to bound their threads together; the default is the process-wide - `ThreadPool.default()`. The backend never shuts the pool down. """ def __init__( @@ -406,14 +396,12 @@ def __init__( root: str | os.PathLike[str], *, create: bool = True, - threads: ThreadPool | None = None, ) -> None: self._root = Path(root).resolve() if create: self._root.mkdir(parents=True, exist_ok=True) elif not self._root.is_dir(): raise FileNotFoundError(f"The root directory {str(self._root)!r} does not exist.") - self._threads = default_thread_pool() if threads is None else threads self._probe_lock = threading.Lock() self._exact_times: bool | None = None self._closed = False @@ -423,26 +411,24 @@ def root(self) -> Path: """The directory that holds the keys.""" return self._root - @property - def threads(self) -> ThreadPool: - """The threads that run the async methods and batches.""" - return self._threads - def __repr__(self) -> str: return f"LocalBackend({str(self._root)!r})" def __getstate__(self) -> _State: - return {"root": str(self._root), "threads": self._threads, "closed": self._closed} + return {"root": str(self._root), "closed": self._closed} def __setstate__(self, state: _State) -> None: self._root = Path(state["root"]) - self._threads = state["threads"] self._probe_lock = threading.Lock() self._exact_times = None self._closed = state["closed"] # --- Backend + @property + def resource_key(self) -> str: + return "local" + @property def closed(self) -> bool: return self._closed @@ -452,7 +438,7 @@ def writable(self) -> bool: return True def close(self) -> None: - """Refuse further operations. Operations already running finish; the pool stays up.""" + """Refuse further operations; operations already running finish.""" self._closed = True # --- paths @@ -706,116 +692,6 @@ def list_dir(self, directory: str) -> Iterator[ListItem]: return iter(()) return _classify(entries) - # --- batches: the operations above, as many at once as the pool has threads - - def get_many( - self, requests: Sequence[tuple[str, ByteRange | None]] - ) -> Iterator[tuple[int, Found | Missing]]: - return run_many(self.get, requests, self._open_threads(), self._threads.max_workers) - - def get_into_many( - self, requests: Sequence[tuple[str, Buffer, ByteRange | None]] - ) -> Iterator[tuple[int, Copied | Missing]]: - return run_many(self.get_into, requests, self._open_threads(), self._threads.max_workers) - - def put_many(self, requests: Sequence[tuple[str, memoryview]]) -> Iterator[tuple[int, Written]]: - return run_many(self.put, requests, self._open_threads(), self._threads.max_workers) - - def delete_many(self, paths: Sequence[str]) -> Iterator[tuple[int, Deleted | Missing]]: - return run_many( - self.delete, - [(path,) for path in paths], - self._open_threads(), - self._threads.max_workers, - ) - - # --- async twins: run the sync methods on the backend's threads - - def _open_threads(self) -> ThreadPool: - if self._closed: - raise StoreClosedError(f"{self!r} is closed.") - return self._threads - - async def _run(self, fn: Callable[[*Ts], T], *args: *Ts) -> T: - return await self._open_threads().run(fn, *args) - - async def get_async(self, path: str, byte_range: ByteRange | None) -> Found | Missing: - return await self._run(self.get, path, byte_range) - - async def get_if_changed_async( - self, path: str, generation: Generation, byte_range: ByteRange | None - ) -> Found | Missing | Unchanged: - return await self._run(self.get_if_changed, path, generation, byte_range) - - async def get_ranges_async( - self, path: str, ranges: Sequence[ByteRange] - ) -> FoundRanges | Missing: - return await self._run(self.get_ranges, path, ranges) - - async def head_async(self, path: str) -> ObjectMetadata | Missing: - return await self._run(self.head, path) - - async def get_into_async( - self, path: str, out: Buffer, byte_range: ByteRange | None - ) -> Copied | Missing: - return await self._run(self.get_into, path, out, byte_range) - - async def put_async(self, path: str, value: memoryview) -> Written: - return await self._run(self.put, path, value) - - async def put_if_absent_async(self, path: str, value: memoryview) -> Written | Rejected: - return await self._run(self.put_if_absent, path, value) - - async def put_if_match_async( - self, path: str, value: memoryview, generation: Generation - ) -> Written | Rejected | Missing: - return await self._run(self.put_if_match, path, value, generation) - - async def delete_async(self, path: str) -> Deleted | Missing: - return await self._run(self.delete, path) - - async def delete_if_match_async( - self, path: str, generation: Generation - ) -> Deleted | Rejected | Missing: - return await self._run(self.delete_if_match, path, generation) - - async def delete_dir_async(self, directory: str) -> None: - await self._run(self.delete_dir, directory) - - def get_many_async( - self, requests: Sequence[tuple[str, ByteRange | None]] - ) -> AsyncIterator[tuple[int, Found | Missing]]: - return run_many_async(self.get_async, requests, self._threads.max_workers) - - def get_into_many_async( - self, requests: Sequence[tuple[str, Buffer, ByteRange | None]] - ) -> AsyncIterator[tuple[int, Copied | Missing]]: - return run_many_async(self.get_into_async, requests, self._threads.max_workers) - - def put_many_async( - self, requests: Sequence[tuple[str, memoryview]] - ) -> AsyncIterator[tuple[int, Written]]: - return run_many_async(self.put_async, requests, self._threads.max_workers) - - def delete_many_async( - self, paths: Sequence[str] - ) -> AsyncIterator[tuple[int, Deleted | Missing]]: - return run_many_async( - self.delete_async, [(path,) for path in paths], self._threads.max_workers - ) - - async def list_async(self, directory: str) -> AsyncIterator[str]: - for path in await self._run(_materialize, self.list(directory)): - yield path - - async def list_dir_async(self, directory: str) -> AsyncIterator[ListItem]: - for item in await self._run(_materialize, self.list_dir(directory)): - yield item - - -def _materialize(items: Iterator[T]) -> list[T]: - return list(items) - def _walk(directory: Path, prefix: str) -> Iterator[str]: try: diff --git a/packages/zarr-storage/src/zarr_storage/backends/_memory.py b/packages/zarr-storage/src/zarr_storage/backends/_memory.py index e7b9f7e335..69b5f0b231 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_memory.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_memory.py @@ -79,6 +79,10 @@ def __setstate__(self, state: _State) -> None: # --- Backend + @property + def resource_key(self) -> str: + return "memory" + @property def closed(self) -> bool: return self._closed diff --git a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py index 27e7ed771f..e2038b06a3 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py @@ -24,12 +24,10 @@ ) from obstore.store import HTTPStore, LocalStore -from zarr_storage._batch import run_many_async from zarr_storage._buffers import byte_view, copy_into from zarr_storage._byte_range import resolve from zarr_storage._errors import InvalidKeyError, KeyConflictError, UnsupportedOperationError from zarr_storage._keys import check_key, relativize -from zarr_storage._resources import Limiter, default_limiter from zarr_storage._types import ( Deleted, Found, @@ -268,12 +266,6 @@ class ObjectStoreBackend: The obstore store. writable Whether to accept writes. Defaults to `False` for `HTTPStore`, `True` otherwise. - concurrency - The limit on this backend's operations in flight, sync and async, single and batched - (listings are not counted). Share one `Limiter` between backends to bound them together. - The default is a process-wide limiter for the store's class, so that every S3 backend in - the process shares one limit, as TensorStore's `s3_request_concurrency` does. Async batches - start at most `concurrency.limit` operations at once; sync batches run one at a time. """ def __init__( @@ -281,14 +273,8 @@ def __init__( store: ObjectStore, *, writable: bool | None = None, - concurrency: Limiter | None = None, ) -> None: self._store = store - self._concurrency = ( - default_limiter(f"obstore.{type(store).__name__}") - if concurrency is None - else concurrency - ) 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) @@ -300,9 +286,10 @@ def store(self) -> ObjectStore: return self._store @property - def concurrency(self) -> Limiter: - """The limit on this backend's operations in flight.""" - return self._concurrency + 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})" @@ -418,67 +405,59 @@ async def _conflicts_async(self, path: str) -> bool: # --- Readable def head(self, path: str) -> ObjectMetadata | Missing: - with self._concurrency.slot(): - try: - return _metadata(obstore.head(self._store, path)) - except FileNotFoundError: + 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()) - except GenericError as e: - if self._refused_under_a_key(e, path): - return Missing(time.time()) - raise + raise async def head_async(self, path: str) -> ObjectMetadata | Missing: - async with self._concurrency.slot(): - try: - return _metadata(await obstore.head_async(self._store, path)) - except FileNotFoundError: + 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()) - except GenericError as e: - if await self._refused_under_a_key_async(e, path): - return Missing(time.time()) - raise + raise def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: - with self._concurrency.slot(): - return self._get(path, byte_range, {}) + return self._get(path, byte_range, {}) async def get_async(self, path: str, byte_range: ByteRange | None) -> Found | Missing: - async with self._concurrency.slot(): - return await self._get_async(path, byte_range, {}) + 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.""" - with self._concurrency.slot(): - view = byte_view(out, writable=True) - return copy_into(self.get(path, byte_range), view) + 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: - async with self._concurrency.slot(): - view = byte_view(out, writable=True) - return copy_into(await self.get_async(path, byte_range), view) + 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: - with self._concurrency.slot(): - try: - result = self._get(path, byte_range, _if_none_match(generation)) - except NotModifiedError: - return Unchanged(generation, time.time()) - return _unless_unchanged(result, generation) + 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: - async with self._concurrency.slot(): - 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) + 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 @@ -509,29 +488,26 @@ async def _get_async( return _found(result, memoryview(await result.bytes_async())) def get_ranges(self, path: str, ranges: Sequence[ByteRange]) -> FoundRanges | Missing: - with self._concurrency.slot(): - 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()) + 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: @@ -557,32 +533,29 @@ def _read_whole_and_slice( async def get_ranges_async( self, path: str, ranges: Sequence[ByteRange] ) -> FoundRanges | Missing: - async with self._concurrency.slot(): - 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:] - ) + 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() ) + 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] @@ -602,38 +575,32 @@ async def _read_whole_and_slice_async( # --- Writable def put(self, path: str, value: memoryview) -> Written: - with self._concurrency.slot(): - return self._put(path, value, None, always) + return self._put(path, value, None, always) async def put_async(self, path: str, value: memoryview) -> Written: - async with self._concurrency.slot(): - return await self._put_async(path, value, None, always) + return await self._put_async(path, value, None, always) def put_if_absent(self, path: str, value: memoryview) -> Written | Rejected: - with self._concurrency.slot(): - return self._put(path, value, "create", if_absent) + return self._put(path, value, "create", if_absent) async def put_if_absent_async(self, path: str, value: memoryview) -> Written | Rejected: - async with self._concurrency.slot(): - return await self._put_async(path, value, "create", if_absent) + return await self._put_async(path, value, "create", if_absent) def put_if_match( self, path: str, value: memoryview, generation: Generation ) -> Written | Rejected | Missing: - with self._concurrency.slot(): - mode = _if_match_mode(generation) - if mode is None: - return _refuse(self.head(path)) - return self._put(path, value, mode, IfMatch(generation)) + 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: - async with self._concurrency.slot(): - 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)) + 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, @@ -711,73 +678,45 @@ async def _put_async( raise OSError(f"Gave up writing {path!r}: the store kept refusing it.") def delete(self, path: str) -> Deleted | Missing: - with self._concurrency.slot(): - 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) + 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: - async with self._concurrency.slot(): - 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) + 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: - with self._concurrency.slot(): - 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) + 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: - async with self._concurrency.slot(): - 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) - - # --- async batches: the async operations, at most `concurrency.limit` started at once - - def get_many_async( - self, requests: Sequence[tuple[str, ByteRange | None]] - ) -> AsyncIterator[tuple[int, Found | Missing]]: - return run_many_async(self.get_async, requests, self._concurrency.limit) - - def get_into_many_async( - self, requests: Sequence[tuple[str, Buffer, ByteRange | None]] - ) -> AsyncIterator[tuple[int, Copied | Missing]]: - return run_many_async(self.get_into_async, requests, self._concurrency.limit) - - def put_many_async( - self, requests: Sequence[tuple[str, memoryview]] - ) -> AsyncIterator[tuple[int, Written]]: - return run_many_async(self.put_async, requests, self._concurrency.limit) - - def delete_many_async( - self, paths: Sequence[str] - ) -> AsyncIterator[tuple[int, Deleted | Missing]]: - return run_many_async( - self.delete_async, [(path,) for path in paths], self._concurrency.limit - ) + 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 diff --git a/packages/zarr-storage/src/zarr_storage/testing/_api.py b/packages/zarr-storage/src/zarr_storage/testing/_api.py index 49ca4415e6..e4f1a5cbd4 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/_api.py +++ b/packages/zarr-storage/src/zarr_storage/testing/_api.py @@ -13,15 +13,10 @@ from zarr_storage._protocols import ( Listable, - ListableAsync, Readable, - ReadableAsync, ReadableInto, - ReadableIntoAsync, Writable, - WritableAsync, WritableIfMatch, - WritableIfMatchAsync, ) from zarr_storage._store import AsyncStore @@ -59,15 +54,12 @@ class FullBackend( Writable, WritableIfMatch, Listable, - ReadableAsync, - ReadableIntoAsync[Buffer], - WritableAsync, - WritableIfMatchAsync, - ListableAsync, Protocol, ): - """A backend with every capability the suite needs of all backends, sync and async. + """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. """ diff --git a/packages/zarr-storage/tests/test_resources.py b/packages/zarr-storage/tests/test_resources.py index bf9911bd64..aa6d925bb9 100644 --- a/packages/zarr-storage/tests/test_resources.py +++ b/packages/zarr-storage/tests/test_resources.py @@ -1,4 +1,4 @@ -"""Shared resources: thread pools and limiters, alone and as backends use them.""" +"""Contexts and their resources, alone and as stores draw on them.""" from __future__ import annotations @@ -10,16 +10,18 @@ from typing import TYPE_CHECKING import pytest -from obstore.store import LocalStore, MemoryStore +from obstore.store import MemoryStore -from zarr_storage import Copied, Deleted, Found, Limiter, Missing, Store, ThreadPool -from zarr_storage.backends import LocalBackend, ObjectStoreBackend +from zarr_storage import Context, Found, Limiter, Missing, Store, ThreadPool +from zarr_storage._resources import default_limiter +from zarr_storage.backends import LocalBackend, MemoryBackend, ObjectStoreBackend if TYPE_CHECKING: from collections.abc import Callable from pathlib import Path from zarr_storage import ByteRange + from zarr_storage.testing import FullBackend class _Peak: @@ -42,11 +44,13 @@ def leave(self) -> None: self.done += 1 -def _hold_sync(limiter: Limiter, peak: _Peak) -> None: +def _hold_sync(limiter: Limiter, peaks: list[_Peak]) -> None: with limiter.slot(): - peak.enter() + for peak in peaks: + peak.enter() time.sleep(0.002) - peak.leave() + for peak in peaks: + peak.leave() async def _hold_async(limiter: Limiter, peak: _Peak) -> None: @@ -72,6 +76,13 @@ def _finishes(fn: Callable[[], object]) -> bool: 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 @@ -79,30 +90,45 @@ def _finishes(fn: Callable[[], object]) -> bool: 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=_hold_sync, args=(limiter, [peak])) for _ in range(8)] workers += [threading.Thread(target=_run_loop, args=(limiter, peak, 8)) for _ in range(2)] - for worker in workers: - worker.start() - for worker in workers: - worker.join() + _join_all(workers) assert (peak.done, peak.most, limiter.in_use) == (24, limit, 0) -async def _nested_async(limiter: Limiter) -> int: - async with limiter.slot(), limiter.slot(): - return limiter.in_use +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 _nested_sync(limiter: Limiter, seen: list[int]) -> None: - with limiter.slot(), limiter.slot(): - seen.append(limiter.in_use) - seen.append(asyncio.run(_nested_async(limiter))) +def _wait_for_slot(limiter: Limiter) -> None: + with limiter.slot(): + pass -def test_slot_inside_a_slot_takes_no_second_slot() -> None: - limiter, seen = Limiter(1), [] - assert _finishes(partial(_nested_sync, limiter, seen)) - assert (seen, limiter.in_use) == ([1, 1], 0) +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: @@ -144,6 +170,28 @@ 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) + + @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): @@ -172,38 +220,6 @@ def test_thread_pool_knows_its_own_threads() -> None: other.shutdown() -class _RecordingBackend(LocalBackend): - """A local backend that records which threads its reads run on.""" - - def __init__(self, root: Path, threads: ThreadPool) -> None: - super().__init__(root, threads=threads) - 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, pool) - store = Store(backend) - keys = [f"k{i}" for i in range(4)] - store.put_many((key, b"x") for key in keys) - try: - worker = pool.submit(_batch_here, store, keys).result(timeout=10) - finally: - pool.shutdown(wait=False) - assert backend.read_on == {worker} - - @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): @@ -215,50 +231,77 @@ def test_shutting_down_the_default_pool_raises() -> None: ThreadPool.default().shutdown() -# ---------------------------------------------------------------------------- sharing - - -def test_backends_share_resources_as_given(tmp_path: Path) -> None: - """Left out, resources are process-wide defaults; given, they are exactly what was given.""" - assert LocalBackend(tmp_path / "a").threads is ThreadPool.default() - pool = ThreadPool(2) - assert LocalBackend(tmp_path / "b", threads=pool).threads is pool - memory = [ObjectStoreBackend(MemoryStore()).concurrency for _ in range(2)] - local = ObjectStoreBackend(LocalStore(str(tmp_path))).concurrency - assert memory[0] is memory[1] - assert local is not memory[0] - limiter = Limiter(3) - assert ObjectStoreBackend(MemoryStore(), concurrency=limiter).concurrency is limiter +# ---------------------------------------------------------------------------- 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(), root="r", context=context) + for view in (store / "a", store.with_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: - """Backends that shared a resource share one after a round trip; defaults stay defaults.""" - pool, limiter = ThreadPool(2), Limiter(3) - objects = str(tmp_path) # obstore's `MemoryStore` can't be pickled; its `LocalStore` can - backends = ( - LocalBackend(tmp_path / "a", threads=pool), - LocalBackend(tmp_path / "b", threads=pool), - ObjectStoreBackend(LocalStore(objects), concurrency=limiter), - ObjectStoreBackend(LocalStore(objects), concurrency=limiter), - LocalBackend(tmp_path / "c"), - ObjectStoreBackend(LocalStore(objects)), + """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(tmp_path / "a"), context=context), + Store(LocalBackend(tmp_path / "b"), context=context), + Store(LocalBackend(tmp_path / "c")), ) - a, b, c, d, e, f = pickle.loads(pickle.dumps(backends)) - assert a.threads is b.threads - assert a.threads is not pool - assert a.threads.max_workers == 2 - assert c.concurrency is d.concurrency - assert c.concurrency is not limiter - assert c.concurrency.limit == 3 - assert e.threads is ThreadPool.default() - assert f.concurrency is backends[5].concurrency - - -def _get_in_thread(store: Store[ObjectStoreBackend], results: list[object]) -> None: + 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[ObjectStoreBackend]) -> bool: +async def _get_async_while_held(store: Store[FullBackend]) -> bool: try: await asyncio.wait_for(store.as_async().get("k"), 0.05) except TimeoutError: @@ -266,34 +309,123 @@ async def _get_async_while_held(store: Store[ObjectStoreBackend]) -> bool: return False -def test_obstore_operations_wait_for_a_shared_limit() -> None: - """Every operation, sync or async, of every backend sharing a limiter waits for a slot.""" - limiter = Limiter(1) - first = Store(ObjectStoreBackend(MemoryStore(), concurrency=limiter)) - second = Store(ObjectStoreBackend(MemoryStore(), concurrency=limiter)) - second.put("k", b"x") - limiter.acquire() # another backend's operation holds the only slot +@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=(second, results)) + 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(first)) + 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 -def _nested_operations(store: Store[ObjectStoreBackend], results: list[object]) -> None: - store.put("k", b"xy") - results.append(store.get_into("k", bytearray(2))) - results.append(store.delete("k")) +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 test_obstore_operation_that_calls_another_takes_one_slot() -> None: - """`get_into` reads through `get` and `delete` looks with `head`: with one slot, neither waits.""" - store = Store(ObjectStoreBackend(MemoryStore(), concurrency=Limiter(1))) - results: list[object] = [] - assert _finishes(partial(_nested_operations, store, results)) - assert [type(r) for r in results] == [Copied, Deleted] + 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 diff --git a/packages/zarr-storage/tests/test_store.py b/packages/zarr-storage/tests/test_store.py index 63582e5066..15d1f4eaa1 100644 --- a/packages/zarr-storage/tests/test_store.py +++ b/packages/zarr-storage/tests/test_store.py @@ -29,7 +29,7 @@ if TYPE_CHECKING: from collections.abc import Iterator, Sequence - from zarr_storage import ByteRange + from zarr_storage import ByteRange, Context class _ReadOnlyBackend: @@ -38,6 +38,10 @@ class _ReadOnlyBackend: def __init__(self, values: dict[str, bytes]) -> None: self._values = values + @property + def resource_key(self) -> str: + return "test" + @property def closed(self) -> bool: return False @@ -117,17 +121,17 @@ 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) + 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 results == { + "k": Copied(4, Generation(0)), + "j": Copied(1, Generation(0)), + "missing": Missing(), + } assert (whole.download(4), part.download(1)) == (b"0123", b"5") @@ -139,7 +143,7 @@ def __init__(self, values: dict[str, bytes]) -> None: self.asked: list[tuple[str, ByteRange | None]] = [] def get_many( - self, requests: Sequence[tuple[str, ByteRange | None]] + 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))): @@ -179,7 +183,7 @@ def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: def test_put_many_failure_stops_the_batch_and_reports_it() -> None: backend = _FailingBackend() - store = Store(backend) / "r" + 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 @@ -192,7 +196,7 @@ def test_put_many_failure_stops_the_batch_and_reports_it() -> None: def test_get_many_failure_raises_after_the_reads_before_it() -> None: backend = _FailingBackend() - store = Store(backend) / "r" + 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"]) @@ -334,4 +338,5 @@ async def _static_surface_checks( store.get_async("k") # pyright: ignore[reportAttributeAccessIssue] store.aclose() # pyright: ignore[reportAttributeAccessIssue] astore.close() # pyright: ignore[reportAttributeAccessIssue] - AsyncStore(_ReadOnlyBackend({})).get("k") # pyright: ignore[reportAttributeAccessIssue] + await AsyncStore(_ReadOnlyBackend({})).get("k") # a sync backend serves async callers + await AsyncStore(_ReadOnlyBackend({})).put("k", b"") # pyright: ignore[reportAttributeAccessIssue] From 1da64c58402870f75bd5641184fa1ef85645995e Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Wed, 18 Nov 2026 14:14:23 +0100 Subject: [PATCH 10/31] docs(zarr-storage): plan caching as a context resource over a tier store The cache is a `CachePool` in the store's context, off by default. Its bytes live in a tier, which is any writable store, so range reads, batches and the conformance suite come from the tier. An in-memory index holds what a store can't: source generations, ages, absences and eviction order. Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-storage/DESIGN.md | 76 ++++++++++++++++++++++++++++++++- 1 file changed, 75 insertions(+), 1 deletion(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 002192178b..709779c62f 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -264,6 +264,76 @@ object-store requests by wrapping the store in object_store's `LimitStore` and s `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. + ## Configuration No global configuration. Every knob is a constructor parameter with its default in the signature; @@ -277,11 +347,15 @@ resources are passed in a store's context. - Listings hold no slot of the context's limiter. - `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. Caching ranges (shard + indexes) needs entries keyed by key, range and generation. +- 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.testing`, pickling. 2. **Remote and archive backends:** obstore (S3, GCS, Azure, HTTP; async-native), fsspec, zip. -3. **Composition:** range coalescing, caching, retry, a sync bridge for async-only backends, URL specs. +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. From 422dee44397404e587bac61869f780a52a5227e3 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Wed, 18 Nov 2026 14:18:14 +0100 Subject: [PATCH 11/31] docs(zarr-storage): leave shard index caching to the codec pipeline Assisted-by: ClaudeCode:claude-opus-5-5 --- packages/zarr-storage/DESIGN.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 709779c62f..0867b09478 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -347,8 +347,11 @@ resources are passed in a store's context. - Listings hold no slot of the context's limiter. - `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. Caching ranges (shard - indexes) needs entries keyed by key, range and generation. +- 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. From b9467df92d0d23167c811d7570d51c1f9c7adfdb Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 20:20:29 +0100 Subject: [PATCH 12/31] build(zarr-storage): wire the package into CI, docs and releases like its siblings Add the package's test/lint/typecheck/docs workflow and release workflow, its Read the Docs site (mkdocs config, API pages, DESIGN.md rendered as a page), `__version__`, and the repository entries every sub-package has: labeler, release-notes exclusion, changelog check, root Justfile recipe, README table row and sub-project card. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .github/labeler.yml | 5 + .github/release.yml | 3 +- .github/workflows/check_changelogs.yml | 3 + .github/workflows/zarr-storage-release.yml | 145 ++++ .github/workflows/zarr-storage.yml | 143 ++++ .readthedocs.yaml | 2 +- Justfile | 4 + README.md | 1 + docs/subprojects.md | 12 + mkdocs.yml | 1 + packages/zarr-storage/.readthedocs.yaml | 54 ++ packages/zarr-storage/README.md | 15 +- .../docs/_static/favicon-96x96.png | Bin 0 -> 12714 bytes .../zarr-storage/docs/_static/logo_bw.png | Bin 0 -> 45208 bytes .../docs/_static/source-version.js | 1 + packages/zarr-storage/docs/api/backends.md | 5 + packages/zarr-storage/docs/api/index.md | 13 + packages/zarr-storage/docs/api/testing.md | 5 + .../zarr-storage/docs/api/zarr_storage.md | 5 + packages/zarr-storage/docs/design.md | 4 + packages/zarr-storage/docs/index.md | 67 ++ packages/zarr-storage/docs/release-notes.md | 9 + packages/zarr-storage/justfile | 31 +- packages/zarr-storage/mkdocs-base.yml | 1 + packages/zarr-storage/mkdocs.yml | 32 + packages/zarr-storage/pyproject.toml | 29 + .../zarr-storage/src/zarr_storage/__init__.py | 5 + packages/zarr-storage/uv.lock | 766 ++++++++++++++++++ 28 files changed, 1356 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/zarr-storage-release.yml create mode 100644 .github/workflows/zarr-storage.yml create mode 100644 packages/zarr-storage/.readthedocs.yaml create mode 100644 packages/zarr-storage/docs/_static/favicon-96x96.png create mode 100644 packages/zarr-storage/docs/_static/logo_bw.png create mode 120000 packages/zarr-storage/docs/_static/source-version.js create mode 100644 packages/zarr-storage/docs/api/backends.md create mode 100644 packages/zarr-storage/docs/api/index.md create mode 100644 packages/zarr-storage/docs/api/testing.md create mode 100644 packages/zarr-storage/docs/api/zarr_storage.md create mode 100644 packages/zarr-storage/docs/design.md create mode 100644 packages/zarr-storage/docs/index.md create mode 100644 packages/zarr-storage/docs/release-notes.md create mode 120000 packages/zarr-storage/mkdocs-base.yml create mode 100644 packages/zarr-storage/mkdocs.yml diff --git a/.github/labeler.yml b/.github/labeler.yml index 482207d6cb..c16ae7db4a 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -16,6 +16,11 @@ zarr-indexing: - changed-files: - all-globs-to-all-files: 'packages/zarr-indexing/**' +zarr-storage: + - all: + - changed-files: + - all-globs-to-all-files: 'packages/zarr-storage/**' + zarr-http-server: - all: - changed-files: diff --git a/.github/release.yml b/.github/release.yml index a66182c50a..5941324bbf 100644 --- a/.github/release.yml +++ b/.github/release.yml @@ -1,7 +1,7 @@ # Configuration for GitHub's "Generate release notes" button. # # The zarr-python repository also hosts the companion packages under packages/ -# (zarr-metadata, zarr-indexing, zarr-http-server), which have their own release +# (zarr-metadata, zarr-indexing, zarr-storage, zarr-http-server), which have their own release # cadence, tags and changelogs. Pull requests that only touch a subpackage are # labelled by the labeler workflow (.github/labeler.yml) and excluded here, so a # `zarr` release lists only the changes that ship in `zarr`. @@ -10,6 +10,7 @@ changelog: labels: - zarr-metadata - zarr-indexing + - zarr-storage - zarr-http-server authors: - pre-commit-ci[bot] diff --git a/.github/workflows/check_changelogs.yml b/.github/workflows/check_changelogs.yml index c1bc2e397c..8f2e89ada6 100644 --- a/.github/workflows/check_changelogs.yml +++ b/.github/workflows/check_changelogs.yml @@ -39,5 +39,8 @@ jobs: - name: Check zarr-indexing changelog entries run: just check-changelogs packages/zarr-indexing/changes + - name: Check zarr-storage changelog entries + run: just check-changelogs packages/zarr-storage/changes + - name: Check zarr-http-server changelog entries run: just check-changelogs packages/zarr-http-server/changes diff --git a/.github/workflows/zarr-storage-release.yml b/.github/workflows/zarr-storage-release.yml new file mode 100644 index 0000000000..019ac5a315 --- /dev/null +++ b/.github/workflows/zarr-storage-release.yml @@ -0,0 +1,145 @@ +name: zarr-storage release + +on: + workflow_dispatch: + push: + tags: + - 'zarr_storage-v*' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +jobs: + build: + name: Build wheel and sdist + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-storage + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 # hatch-vcs needs full history + tags + + - name: Install Hatch + uses: pypa/hatch@f647ed70d49adb885f53a27d1c7f5bdaeacf2c60 + with: + version: '1.16.5' + + - name: Build + run: hatch build + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: zarr-storage-dist + path: packages/zarr-storage/dist + + test_artifacts: + name: Test built artifacts + needs: [build] + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: zarr-storage-dist + path: dist + + - name: Install uv + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + with: + enable-cache: false + + - name: Set up Python + run: uv python install 3.12 + + - name: Install built wheel and run import smoke test + run: | + wheel=$(ls dist/*.whl) + uv run --with "${wheel}" --python 3.12 --no-project \ + python -c "import zarr_storage; print('zarr_storage', zarr_storage.__version__)" + + # The sdist has to stand alone, and `hatch build` above builds the wheel + # from the source tree, not from the sdist. So build a wheel from the + # sdist with pip, which unpacks it under the sdist format's rules (no + # links out of the archive), then run the package's own tests and strict + # docs build from the unpacked sdist. This job has no checkout, so + # nothing comes from the repository; zarr, where a package uses it, + # resolves from PyPI. + - name: Build a wheel from the sdist with pip + run: | + sdist=$(ls dist/*.tar.gz) + uvx --python 3.12 pip@26.2.1 wheel --no-deps --wheel-dir sdist-wheel "${sdist}" + + - name: Install just + uses: extractions/setup-crate@7577c1bdf2d95e6d65d532788f35ed79d4b1dda2 # v2.0.1 + with: + repo: casey/just + version: 1.58.0 + + - name: Test and build docs from the unpacked sdist + env: + UV_PYTHON: '3.12' + run: | + mkdir sdist + tar -xzf dist/*.tar.gz -C sdist + cd sdist/*/ + just test + just docs-check + + upload_pypi: + name: Upload to PyPI + needs: [build, test_artifacts] + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/zarr_storage-v') + runs-on: ubuntu-latest + environment: + name: zarr-storage-releases + url: https://pypi.org/p/zarr-storage + permissions: + id-token: write # required for OIDC trusted publishing + attestations: write # required for artifact attestations + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: zarr-storage-dist + path: dist + + - name: Generate artifact attestation + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-path: dist/* + + - name: Publish package to PyPI + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + + upload_testpypi: + name: Upload to TestPyPI + needs: [build, test_artifacts] + if: github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + environment: + name: zarr-storage-releases-test + url: https://test.pypi.org/p/zarr-storage + permissions: + id-token: write + attestations: write + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: zarr-storage-dist + path: dist + + - name: Generate artifact attestation + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-path: dist/* + + - name: Publish package to TestPyPI + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + with: + repository-url: https://test.pypi.org/legacy/ diff --git a/.github/workflows/zarr-storage.yml b/.github/workflows/zarr-storage.yml new file mode 100644 index 0000000000..2f1ea78546 --- /dev/null +++ b/.github/workflows/zarr-storage.yml @@ -0,0 +1,143 @@ +name: zarr-storage + +# Job steps delegate to packages/zarr-storage/justfile, the single source of +# truth for this package's verbs; CI owns only the python matrix and caching. + +on: + push: + branches: [main] + paths: + - 'packages/zarr-storage/**' + - '.github/workflows/zarr-storage.yml' + # The docs config and header script shared by all package sites. + - 'packages/mkdocs-base.yml' + - 'packages/source-version.js' + pull_request: + paths: + - 'packages/zarr-storage/**' + - '.github/workflows/zarr-storage.yml' + # The docs config and header script shared by all package sites. + - 'packages/mkdocs-base.yml' + - 'packages/source-version.js' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: pytest py=${{ matrix.python-version }} + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-storage + strategy: + fail-fast: false + matrix: + python-version: ['3.11', '3.12', '3.13', '3.14'] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-crate@7577c1bdf2d95e6d65d532788f35ed79d4b1dda2 # v2.0.1 + with: + repo: casey/just + version: 1.58.0 + - name: Set up Python ${{ matrix.python-version }} + run: uv python install ${{ matrix.python-version }} + - name: Sync test dependency group + run: uv sync --group test --python ${{ matrix.python-version }} + - name: Run pytest + run: just test + + ruff: + name: ruff + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-storage + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + - name: Install just + uses: extractions/setup-crate@7577c1bdf2d95e6d65d532788f35ed79d4b1dda2 # v2.0.1 + with: + repo: casey/just + version: 1.58.0 + - name: Run ruff + run: just lint + + pyright: + name: pyright + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-storage + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-crate@7577c1bdf2d95e6d65d532788f35ed79d4b1dda2 # v2.0.1 + with: + repo: casey/just + version: 1.58.0 + - name: Run pyright + # Pyright runs unpinned; the interpreter pin lives in the justfile. + run: just typecheck + + docs: + name: docs + runs-on: ubuntu-latest + defaults: + run: + shell: bash + working-directory: packages/zarr-storage + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install uv + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + with: + enable-cache: true + - name: Install just + uses: extractions/setup-crate@7577c1bdf2d95e6d65d532788f35ed79d4b1dda2 # v2.0.1 + with: + repo: casey/just + version: 1.58.0 + - name: Build docs + run: just docs-check + + zarr-storage-complete: + name: zarr-storage complete + needs: [test, ruff, pyright, docs] + if: always() + runs-on: ubuntu-latest + steps: + - name: Check failure + if: | + contains(needs.*.result, 'failure') || + contains(needs.*.result, 'cancelled') + run: exit 1 + - name: Success + run: echo Success! diff --git a/.readthedocs.yaml b/.readthedocs.yaml index d079f62d5a..2b54934a80 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -27,7 +27,7 @@ build: if [ "$READTHEDOCS_VERSION_TYPE" = "external" ]; then git fetch --quiet --unshallow origin main pull/$READTHEDOCS_VERSION_NAME/head || true; - if git diff --quiet origin/main...HEAD -- :!packages/zarr-metadata :!packages/zarr-indexing :!packages/zarr-http-server; + if git diff --quiet origin/main...HEAD -- :!packages/zarr-metadata :!packages/zarr-indexing :!packages/zarr-storage :!packages/zarr-http-server; then exit 183; fi diff --git a/Justfile b/Justfile index df96003eef..7c338749c1 100644 --- a/Justfile +++ b/Justfile @@ -164,6 +164,10 @@ zarr-metadata *args: zarr-indexing *args: just --justfile packages/zarr-indexing/justfile "$@" +# Run a zarr-storage recipe, or list its recipes with no arguments +zarr-storage *args: + just --justfile packages/zarr-storage/justfile "$@" + # Run a zarr-http-server recipe, or list its recipes with no arguments zarr-http-server *args: just --justfile packages/zarr-http-server/justfile "$@" diff --git a/README.md b/README.md index 50243cbbed..43ff9ad1fb 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ In addition to the primary `zarr` implementation, this repository contains other | --- | --- | --- | --- | | `zarr-metadata` | Tools for Zarr metadata | `pip install zarr-metadata` | [Docs](https://zarr.readthedocs.io/projects/zarr-metadata/) · [Source](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-metadata) | | `zarr-indexing` | Tools for lazily indexing chunked arrays | `pip install zarr-indexing` | [Docs](https://zarr.readthedocs.io/projects/zarr-indexing/) · [Source](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-indexing) | +| `zarr-storage` | A Zarr-agnostic key-value storage layer | `pip install zarr-storage` | [Docs](https://zarr.readthedocs.io/projects/zarr-storage/) · [Source](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-storage) | | `zarr-http-server` | An HTTP server implementation targeting Zarr data | `pip install zarr-http-server` | [Docs](https://zarr.readthedocs.io/projects/zarr-http-server/) · [Source](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-http-server) | See [Sub-projects](https://zarr.readthedocs.io/en/stable/subprojects/) in the `zarr` documentation for an overview. diff --git a/docs/subprojects.md b/docs/subprojects.md index 9f7951e836..61983c15d5 100644 --- a/docs/subprojects.md +++ b/docs/subprojects.md @@ -32,6 +32,18 @@ without taking on `zarr` as a dependency. pip install zarr-indexing ``` +- [:material-database:{ .lg .middle } __zarr-storage__](https://zarr.readthedocs.io/projects/zarr-storage/) + + --- + + A Zarr-agnostic key-value storage layer: sync and async stores over + memory, local-filesystem and object-store backends, with conditional + writes, byte-range reads, batches and a conformance suite for backends. + + ```bash + pip install zarr-storage + ``` + - [:material-server:{ .lg .middle } __zarr-http-server__](https://zarr.readthedocs.io/projects/zarr-http-server/) --- diff --git a/mkdocs.yml b/mkdocs.yml index 58b5d3344a..4a8a4add0d 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -102,6 +102,7 @@ nav: # keeps the reader on this site's domain. - 'zarr-metadata ↪': https://zarr.readthedocs.io/projects/zarr-metadata/ - 'zarr-indexing ↪': https://zarr.readthedocs.io/projects/zarr-indexing/ + - 'zarr-storage ↪': https://zarr.readthedocs.io/projects/zarr-storage/ - release-notes.md - roadmap.md - contributing.md diff --git a/packages/zarr-storage/.readthedocs.yaml b/packages/zarr-storage/.readthedocs.yaml new file mode 100644 index 0000000000..ccfa413bfd --- /dev/null +++ b/packages/zarr-storage/.readthedocs.yaml @@ -0,0 +1,54 @@ +# Read the Docs configuration for the zarr-storage docs site, separate from +# the zarr-python site configured by the repo-root .readthedocs.yaml. The RTD +# project for zarr-storage must set its configuration-file path to +# packages/zarr-storage/.readthedocs.yaml. +version: 2 + +build: + os: ubuntu-22.04 + tools: + python: "3.12" + jobs: + post_checkout: + # Cancel pull request builds that do not touch this package. Exit code + # 183 cancels the build and reports success to the Git provider. Scoped + # to PR builds ("external" versions) because origin/main is only a + # meaningful diff base there. The shared docs config and header script + # live outside the package directory but change this site too. + # The diff is taken against the merge base (origin/main...HEAD), not + # against the tip of main: a two-dot diff also reports everything that + # landed on main after the PR branched, which made every PR that was + # behind main build every site. The checkout is shallow, so fetch the + # full history first; without a merge base the diff fails and the build + # runs, which is the safe default. + - | + if [ "$READTHEDOCS_VERSION_TYPE" = "external" ]; + then + git fetch --quiet --unshallow origin main pull/$READTHEDOCS_VERSION_NAME/head || true; + if git diff --quiet origin/main...HEAD -- packages/zarr-storage packages/mkdocs-base.yml packages/source-version.js; + then + exit 183; + fi + fi + install: + - pip install --upgrade pip + - pip install ./packages/zarr-storage --group packages/zarr-storage/pyproject.toml:docs + build: + html: + # Build from inside the package rather than pointing `-f` at its config + # from the repo root. mkdocs resolves some settings relative to the + # current working directory rather than to the config file, so building + # from elsewhere looks for them in the wrong place -- and silently, since + # the paths are valid, just wrong. zarr-storage hit this: with + # `pymdownx.snippets` and a relative `base_path`, its snippets were + # searched for under the repo-root docs/ and the build failed with + # SnippetMissingError, while `just docs-check` passed because it runs + # from here. Building from the package directory makes this identical to + # the local and CI invocations, so a green build there means a green + # build here. + # + # $READTHEDOCS_OUTPUT is absolute, so the cd does not affect it. + - cd packages/zarr-storage && mkdocs build --strict --site-dir $READTHEDOCS_OUTPUT/html + +mkdocs: + configuration: packages/zarr-storage/mkdocs.yml diff --git a/packages/zarr-storage/README.md b/packages/zarr-storage/README.md index 0843002d86..249d1803d3 100644 --- a/packages/zarr-storage/README.md +++ b/packages/zarr-storage/README.md @@ -1,3 +1,16 @@ # zarr-storage -A Zarr-agnostic key-value storage layer. Pre-alpha; see `DESIGN.md`. +A Zarr-agnostic key-value storage layer: `Store` and `AsyncStore` views over +memory, local-filesystem and object-store backends, with conditional writes, +byte-range reads, reads into caller buffers, batches, and a conformance suite +any backend can run. + +The API is pre-release and may change in any release. + +``` +pip install zarr-storage +``` + +- Documentation: https://zarr-storage.readthedocs.io/ +- Design: [`DESIGN.md`](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-storage/DESIGN.md) +- Changelog: [`CHANGELOG.md`](https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-storage/CHANGELOG.md) diff --git a/packages/zarr-storage/docs/_static/favicon-96x96.png b/packages/zarr-storage/docs/_static/favicon-96x96.png new file mode 100644 index 0000000000000000000000000000000000000000..e77977ccf41426c35a768ea73ed20e05d2676dd5 GIT binary patch literal 12714 zcmV;bF;&iqP)pF8FWQhbW?9;ba!ELWdL_~cP?peYja~^aAhuUa%Y?FJQ@H1AOJ~3 zK~#90-F3TWhscfoy={Ravrt z)mGbDaM!N|6a)bkEvSfq;)-mtg)E=~30t;v=6!yD+$3bVL2JR~_k2F*lbds%GiS~- zGw;m2vm7CbUmEfsOgmc?cSkhjxbhO*YmAwH+PyPA{Hf#h-$H&#;_nMi>T1C>A#Z}< zP((4?ltr=*xFNc>6^ z+?O^2!gH1KT*3o0zxWZO{9nO*H|592H^KDw1^1;rWyEX(Fd`g>WPYjZdLpLthTCuV z*JYSb025U(HFfO1;H0jnILbc=zMnb*)sY)ajdNTCMdTI$Awda1D*lF$M_{@E_LfCQ zGr|@Zw{97@dGD0;qSo7XEXKTf764#@gomcD1F)`ON?PxNdsD}XPgb;^I&;sD{$lmu zXJK{auVKG<*N+*K0(r!WtTEJk0CW`MFJW6dT337kC`d~iAwYYGd;_wShLK9M zL&zi}a;)`?koZ;nNvUH&Bv3IoJ|iRVCaUIBWjOtPl{i`b4x_pmOQ3Rdl;hss6U9D%#n4`w5hXowfcp9^n~PN_psKm;y;Cka^q=&hj41MmP?OZdv1FHiz6Liw~f7(to^Z32Og<;3YA_9*N* z1<9#BVXzvI>WK>gIBn+4FY{B<&J#)pQ1?LOjJ?Te=cwq1rn&(j84oPQuwhPqQitE| zO-Tzty*aJ3v-h7=k#LgD&i>TYCi&yjrZjM|i^RRK2#HYhP@niVsPals8bJ9vtlR*F z3Bv^ls5R?hUV_!G^k2Xq`Rt zT>$SEj8E=QFoJ5_f_qYKg|RE*X3feCakY|;gxMME0jw{$C#8>wiM0w8+?_gB$#)YT z$@~fc)G9>9#?Q`JgkaE@SEPgU$EP-F=#?ytee}`8|Eq5QQ_kOedoU{h?$imk-03gM z86cWfRfv@!D3pal3^2sE2An5WT7mG_s6dbNLCBj_UI~?rs`9v6Z4aVh4Sp@NQi-_P zS#KF@0swo0BJ_Nh6x@??>+U;K>QuA<5chEA`>Hri$j$%&F+B_JP96L8T@%~Zc*fMJ zUc$o}uSELsN{KWak$+F>-3P~wYx+aA1Ad_RyT=3@16ph20qY7cfO4xTW$~AE@QBMh_2o~@=xSYg( zp>gVv6#(UfxW8n~H6Fi)lAbYr#bOsM8&;>5x~@ks5{l1C*x-u1Kc(IL?VZ8KKSam> z%Is_(H!d;?4S(lvjC4Tas=5e@TI~~gOMz_1N)wXvAyqA%diYqY8@wJT~5+ z{BbFxt>?U&^!SXz+V2?mw~Q4Kk-R&TucR1j$d(0vN*&{Ke9Kz?W!l%3@i!`N>&G(Y zZyz@<(ik0*H!juZltnFU{m-ez-&fD?CH|&i!HDSQ#kV#z4f06*wGQEU({VL~86bK% zz|#Qk2GFFIaK{A&KBnPxQ6vdu2FS+&G^-Q-@%uLum?lIM5lr2`r+9@lkRAj-DaWzv z^8T1sjt1om4I--Q0sz3gc{Tx9n15%=C<=aMJlWtt2j}0J!pKrthz3&2^pOc7%k%C? zz6(ZLgWT@A?iKlWrWkSjZ_%~` zLh(1;e!IW5FEA>)Ii>(;D=wogqhtuNs4Ha{5j<=>uq%V`qWLW?<2geo5owe9Ywup9;#Ff@--kqJffs_S)| znp;KrN2(m7CmB@!4a)fHHoOMkA_vN;fXRoIG*ae5(Y^*BK&z~*V+oJXe7>QtWFah6 zU6VsaWZoSq*Vgd$SCod1k3L!!_xG7EG1B`tJyR~qy|8Rva7WsR-D85so2ZrVJawv< z@L0wxMf;;(5H+O+*e9@U^Z$@Cs)oH+0C0*E9-sN5bIdOBMV4Hbe@EJ|O~Zl_;bgAq z+Zi^@$q%%7m-WEt5-%g}O$hY%EE#J=X(?*bbF^sGeg%N|o z)`h#4L}$Q0PR8-5Vq8+alRI-cTnUoiOHhu%8<7* zyg5?cFEA4b%>j@O$azrghVbohd;p=GS?9q3XjVDatW@LuR;@HCXxjD`T2l@Q(?+!b zMcym}R!3T14PnEm;s!Sna=1>DHV;5kKxmd4*M8#qoS`D>r;WHughd{;h7zSFqSSA_ zrcn9#G>yI?Z*0o3grr8VV(L`SFp=cK#{mCj*{zaod^?~LaZ!D14v%oRnu zdd-DmuMo*jnSKq$?PB?YD7)6%WK|+2vH*(nPGG){h~kmvNl_($iO(C8 zeo1XHVS&@0oc?XxoXjVccpDZls=J`(^xRw1uBhSbuP`s||2gwe{M^iE;X1F;Le-j0 zqDU$jojMr7psB$J(CXQ&V+l{rd_EHLvawXU*lLvB@^4MOuFBjMhxnf2Q2gA?XSLM% zPkv7EO?kH@4>eGkN5z@7Y;DDF$rmekiIp_5@@J}^0Y#@e;vE-fzfh8?dZ#LeQFs;< z=hVli%3)F556UPgFK~#yu(CrG?Tg6Xl;Ak0bL&rKaYOPW^Q_e*81j55zy6^^BKHlHac%q%2iHG zw7{Z9iEBPL)R{-{eH638lsC8N3=Db^yhx+I_)x%GEVMby6lNrwdPD5X~o}xky z33(5|JPOhQoC_jUJ=f2lB1S%^GF4#u04S}`91%Qf1T#s#1IpbH-Y>vD0xQFiA!15J z@K=yaK>33TUI$PF0Alfu^;%$t2M{<)0%TwnQ_q-=spiUDFkCg$Iq+N)Ns z0stgDGdn--`OGJcweQlS0$6KZ?VLBVmbt6ow|+5uf828!Pr0RBK@T3qZ18#7Gw;Tf z0afPC0zN7Mq6oml0(`6n$=1VG5!Q?d0Hs#mTMXiFbj*Lm>NpqP22r`Jb}bs}$Pxg` z0sPA-7pXBLDB6$Y;OcY&5K&arS5|=M0C`@)%Sd}QEN-ZiIrj^yx!Mq4&}d_BtKuFa zx{~C-;WOhBo)0rJ6$~1GX+(cghteRQ$}2&vhvCt@8lCXV(uXjL?|(4hwXESQwr5b6tdKSe-zc^3Vojl#}|qV!CWE!kKkw(c>|V* zA@W|>){a1-_&;O#q*AU2xZD8wM4chTs&~-p@~r?b zmAk(8{eJH%g0BPc)!SSQ`7&2ndapSW(M>I011cPF_2b>6u~Dw?$g!b$Ulcz;%6gw; z2DY9TW?oJ(XmYJw3&HKI8N&xNd^REtvI54L*Q2^RjjU zn3I3agidsv(|k}2I>8Hi0zLK^;shcpAqyO%|FYH$^!eONpr~(3NCjjm z$wx)xT%Y&`Q#q~{>@Sbs>%`pL5sEF-V)K-0@EAB0uaXl++QCb!ZoDH5Mfs+<_gVH&zRwD z7tYvShd*qXlkc{>k!(9jz-?A^WYWUy4Rv_c!?$%$3t@zK4;CcY&cO86a(@#cYKU2# zujDd^zDR|3HIN=)L`x{j>V$8B+Ts(!mmLS|)WdHGE=BF)Unj9-xsr;*R?M=9Uy}77h)C|h)XT-#2!*rO zSnZ#Cb?VNqwaiVZ1f=Dp5T69pQgLVwy1$ZA$&~ z0enTGU*fVb)BG+C`f{U=-7Ha<1jXk985X}JYqBaafI=x*eax7fku8CadrL`DGIGyx!DGXh{JwA9s2?4#6l5c zjd!JZXaa+<=8M+&NnH+yiJ-*MaV~}8LLV&N2k??8qN}oLcysZg&*l4`-+4vAIRsi9 z4?P^8TaEhPQt@J;d>B9iLph@;%*Yf-6j;YwY}8*SlqnQl56FPTH?zK~9rC7O!HA}X zM{jA>EIL(Od}JMGNYd*wzpVS($5HT`2|d*K?(j$Glvcnu0I>Vgdjh@)|8!6vH3~O= zMb@J2SB;B|w2?zWX&~0DQnA0;J2?13>%|o#RCxdz0kl3%S}}7GE)Dwfe8;W^#1Y8H zMse}>tHyoRaapwib_>vPn7C}_as-2>V9n8i0(|6yMX+vC)e!S@A*WHKl{%)ESZ03* z|0@xh1_jl4{YCM39e#E3iCi(9Mo5w4`sV;RC}Ic4ub8zhoaoU9kB(_dNdaW7QU@o! zmA&aiqUZLX_$$!dD{uyha(Jt^v%aak<~aUG#NtV)DXpx`Ixc&(48TiYUy-@6(D)3ChZ(7gVsp5M_$C_!jg zr?Ny;3~lE2Paff8m|{{ANiE#!R_9T<*R9r>3eU#Kwm z0wxhaF@cv7R%OnwN|Z}ehk)oqgT<<7##+Nlt=`No&g+*PNlFftO#u@b={39&k?PhS z%mILM(lZtfRm=vXHi{O3$2T&9l*L_QfyGV=@%1czn2<7Frt7dJjEqZRhlshAjHrN89 zm$7z0(yGjnClWsQl9Y>bFHTvZioc6;u5mFEik4FD-Broick!eauzZ-rU)7Z;()&uA+0PG=Tnt>LBvY&$GbzhA`0I3|Y`kKTH00nSZDk_U>kxL;M4dSJW z{|f=m0^~!0v4B)AT-Yy$gQ)T#fMyEb$B4#n`^t~~4!{HgD}~Oqgf(?5-0H~hn|i4# z?}JDaKp#w8lf8J;nfLn}M;}{f1d|h1XI72O?dg-U0OabVHCcbj>pebR;rq2Qh@e6t z$V+@b^G%3IUhm|)l(H#l&GC_}+`g%CAg&-aLLe@T>`#0@>a{(6OQVh2o7L!=r1y^Z zDfV2H-X7NW1=vu;lnZz`A)?W%x#dT%^TDD(C^KmIt&o!m>0TjneeZcdh)hDZi7*X7 zPbh|jWePyz2!MwTunv$31SXQ^ZmFD^MlfMr);a)}=Uy=JVq;_)N{+oi;AJ@Yb>jOc zUO|%EE9G*4_X6Tq^1(LivzCD*kcB3_QtqXPj}q1$7e4R8)SHB8mbk9*qX3YwW_JFb zUa1YJ@QJWoRa)itO1V`pn7G@i-qfsoC3OoyUt`kj1=y5|=)4P#j*)UH4%gaYNok4W zL^LJv84Nq9O5&8L=2g>S%a;36|YqSuqmC+DDOr*+3VgNe+VQLRj{!m#-|b zaMp>d*Nf$^Xt|V@mxZp|Dqi(LD2HC?Y=bF0E(vs_+9hW8AmGbWtsCYSp3Ja{B_=W z$!AsFP%XD6Y?!@0;iK$1>hWW-Or(XEcmBlN^3G50d0fon{P?vQc?ln8%@xQe#xqHx zFnQ-DkIg$brC$wxdFW?{&$7NrT%Yw+sKTun@2qizB2)q^vtZ>~u{eh+%fyqY6Y$HS z_&bT;(&}l(VhLR|frW&<$HI!mb5PbC0;eOewZxa8$vZpc+T61zegfhlS~&F3LR^kA zR&Hzm(ab~D=}zI%X>esl!iQO_D$ngXXTtB`!4FD4J)^KVEAQ-yx9vV_VrPUgFG-)w z+AJz9M70@QKs|QKJA2}7TH-smD#KNec9}0f#Ai7y1xc=T@{YF+?LkrY8 z%A`y-Q8Ad7ZE5+sS`1``XkqvsJlROdd!P3y}Og;j`>HVx7&_ z0`RoGTHQj=v;12c(#2FaxKT23&>L-=c_?WSiFG~Po&jQ zi^V<#N<7poN9|c+H9KDfuviWL;;6I)u~;e=!x6X=RtDsDOfF)+~ie3@rTh@F5n{rD;s61Oyr`#fnEwF3` z%OY4buEux8no$Y4HRnSXdr_I<$^3+k8S5+0<#syqXYtT7!sVMa%wz@HY|L0GibPm; zhXOv=>zC6x<<`7T_r!%WFLFdbgq5~X(;6ytXfMb)W8!Ua-S*+!^H$t#^w?G`{7}I0 zO!u75$zw_BVn7UlMJd!QhstQ!3QuRa!@~}-GC-{ChGH=lcflgEKE5ixqALSwFR_adma{;)zrp=bDx$sy3 zH3}Eq#MNB7PTe{CEfca z6_*Bm#>F!r|NKp}BTHKxj2A4KmEhZJYF4 z8a*m1347X2yv2CBBq6tAahx8HPtuNAZ$m_K+fKNehDU@<%xRxImXxJ!cV+HFF+#?> zqA#4ZJ@b74@8@<%9&c(F{~D%1@eUP(V6jG(FTvILTE)Ni@e!5RQn?TwA2%vVu!yO{ ztIEmzQas)$9_LVTFFZLD7N^zEM+w#3Qr#sC06x$A3oPa&?3i8UPR`kNBn?)!Chp2! zblyk*bdz>w&Zk8?B`*+b7KkT9V5AGk zX90v3g4H((N|^^E!y(d2h`#}7jT20o0+eW;@&-<=Ef!c7GeTcOi$xtzd~z{ z2wK3<62}kyn5x&&)nZjXK~HDUGPd%%wLnciHdA@CQ7xy{EPDDVEn6Sw+gg0?R;%}r zIH;;q;Nf4iXiG~_301Am^6qn>5y|;@{M_k;~S^YsFeT!5i3bVK~&b@1EG?WpS|dt z{6jB@WvP0)hpOH8w4N|(Ym3w-l~FP909b6KCpW;wlW^q`b)Amz&=MX{&#{A+V`z~D z7Y}%z(;l8A)!}K??>xHvBRxzK54W*Q&Jq`=*WtSWJa}U9jAKn#@wm{c87D69wPn6B zHCzG!%F6K=TzNR*o6M>Kmxx0V_rt@N;z|rGN-U*GPK$}R<;Es=tE%WLaK^V8N0Ro= zde&H;4HrGsMWbddn%R#5lSD)|_iBJ5e>lE0f{7TTU2mOG_f4 z74J}i^Y~AfuD%Ux&V?&+YGES9yEdoA#G6Dl$|oL1!AJv;GXV+tG3qfF2C^T*+d&os zG8w2?!B-#Om;9n@H@m$DE<0Mu`39jg93ih`-m_3;^EeOQ6EzEwVhVU&@PJ_yHOW&=P zj~snKtH9R&F*I72UPd0J-OahJ0-_~?u^9X|p#wR05{7c2@*8X5k$J=%p7inT5t|xJWKt6`h zZ;#I(ssXF|h6A%x!OO(pH1CKrN&wfb$MND(7e)A;y`HOA3MAI^crA$1@-UOE3?Zm? z941WA2zQVeppZorxv=uO7gDbJQLG}_bg+$L&apJh2x1f%+7+98Gl9cx3$tFWett)@35g0!f$RT$m5|NGH5HL3puP#V@YuaR z$9zh0Tm!FL+rq41b>TNjFk)wH${i-qV2jZ7q?*f>=02r~CCu)fF)6q1Za%SdB|l^? zd}vdYwX0oG)?9kJo)GIfe9tJmZf}-+VJ$fU0Eypb6tpYKnoBXOlq{!l)*98GI|9j< zRV69_Uq#(_4CJG9~&=^b4EILx0KuJR#&_0C$k)Tz~_^MB+W#avWsh65D^BF=aQ1v@o2?jWB||x50hwQjXnv=QxWQ( zm2jx$HZ7YZ7||f6_|^sirjT4MDwnrA6lx*u45TIzI71Xysc=2jG}{@Ia;s@JVNLBm zQ2WEPw&f*`&(&l8u_|Z@YRS%+lrErr?t|G;+qKjF;LJTaE$&(DS#vGG7#fss4(xd`rpBE7=6{5_oTM#Qzi6Hv|<$QX)Lcs}`T9lk(e^a}vpNz-0D9Z4fg zJJd2Sbp(z{o&)gijt6RPEU`T%Tu_=QD97f3BJnPHue0chS+M@fT zkB*55NU9R=8*2x2I9zv1iU>D%D9oC?EjslABfOd->!_v~)oi0MrZ&GKs&A5dOzE5l zqn%x#7eh-KYoHh*Yft06qT*Sjrmv;66+t&2#UucHgE(HB3k+&aOt%1@mvY|*`0e!& zE@!m`)V25uVxBnmLDJVwlzr52=@~^?VRL$QY>P>`6O=DI70z5${rvVoN(YME?b54S zu(74-q-KsIfAz%l?p#=Nmf8ln-QOfSX0$)RG{AgdEv`J{a7K-p5tZ-&NX4EfoeqU| zBH7+7`9fM}5FP!1F#EO#QpZ}w>dG)G3q+^FS)Ty-%r_zr zl4z^extT_no>7$fouXHW*~vJ#B_h!9q8b+@Xfz;CLFCU}tCjLgpbxgjrt}fzKs8(~#0PCt~j z?u$VBwn#cR2pFUEox3%VdZCi!&23?k$; z5Rm|uhwF0Cn$6a)XZeY?YUL&vF6&g3@x4R`fK?LowGQZ9rTIhKT{V}>ZwZv%1CcGA z56-Nb%Ca?(HVi=08HaY=1cXFy932?dI1rN#a=kbh)MeSgMxioP|v^jZX%Y=E_J zd_z0!e<=S%w{!~i9p2j#lhV)7xx%Ba6k++cK>BSSv8wB#nsbWID9l(1VC9xT`sD(R zpvZb3amn^(sfRiqIKDKeXzS-umObsG>(j{E<6CV3Y4UgvZhNl;Wx!h8Y9GSAm~Do zk10B&>wy!`PKE@{mYCAv3}6C)cj=SCUA~>Z_lL$A0M00!wi3X~&4Kj(N?c(CZ(5qB zfaC~l-F?^$BLS`;O*;shIevQuA$@!xmMHiXfabMFyDNVRxX_9dG_-B3%0)1;yz37z zFSSu}sB{7e*LtRgY1@jluwom>`XIxcO)(ut zAi(h;R;lX@>{h*ha1zj^XvSLr-r5*QzuW+q2=sLkM>fTz-)f0f-HSr2P!s?J+V$Y{ z#j7OfYZWN{EhuYcV<0_T6MYC_77An$VS^%0oGLCdhReGioc`X)iu|U)m$8#ag!Ao?;_NcSxmM6x)ETa@uXq0+ z%u9W+hK@k~-tFM@J2%HnX=BOjJn9^QY&-MN^ct%MyB(ZSdw1~~SS3MUi$K{;odX^J zOu-7z#eg2Q{6eQ1T@TE79l+}wV2fRz+LpcCueG!;+nBb+~I}iz)FQVORn+2F=fz>|0cU9MKe*8_T ztE1b&X-fet{UUI0e~1huu!t&U8)GKlYE<9tdT7S>O5Y9vECCUO!E9jf$$iB!V|x!v!NZhng| z(BdutOZ@7;tm~nvr)vJp;k4Z~Hn^KF!<^G&Iu9q&MFsQDJNUpU z{mjwlv6H)5$~}Ob1Hl|8qV!oUi|kLz@Fs^2jX4|>eVY)!2l%pz_sDs*Mx=fT*d)P- zvS@E41&K=Ev*#C0ty+N|_RA6TWth`3rqeK`=_+F9pL=lH=ch7)8=3~2!{_}@h#Lgl zN1z=b#RASRH~vR^9+>(+ZyNn$V}so8H-T0o0kl!_+4G7Xth37I#Gmbup!q1q4l^p< zL^!`k;RD}qN&OGRDhc`;M|(pI(5}Q^{*ON2R?MaR1!05S?w3HTn+UXXl+T}Y=)pRR zxGVAfzL_FH^I?n*6yPFNJMV&`hkh~NAN;YfL2mbJOsnCd=mO=l=O2DB?BGpx{C6L$ z5s?pL?i(bKzO=gFSBD<>#eIqMq(g${qi7wfkaHcMJa^vyso!JprsCEg^tGUhL?EQE zvGVfyho-Lo?wkHUg9OdGXdMc{g#tcz!4ELW|J$dUsuBTx)N*03Ll3O`;eq`^AVIS( z8rMLymw|cySA|nQ{lP()5xJn^Q`V`)` z^1JW&nL&bPZHx>gc(GCQQqQ7$>))g8hd$y|f1Yn`AlP38SAtmDyJ+fvPU*u=1_ZJ? z=7B*Dc#$gR^(mTq%9_J_l~@%! zt*@b8LE-v-rzjCt1s>`zqE``S@g;>*R-KAx{5Sa7h+m0SvD5krc{xNr?00bTNlAo| z=)4l(YyEyk&EB7#_?1`{JFPFt%gz6g2$iB+%F@eq9mt=MUOjdB2t zth?+anXFTZUyS&b_)oKGz18w61Np2n5#EZO))&eF<`*J*C4O<@S7Jr%j6P5f6i@_w k``1NN-ukKI^xxwD0dx|tMUqFQ>i_@%07*qoM6N<$f_TPca{vGU literal 0 HcmV?d00001 diff --git a/packages/zarr-storage/docs/_static/logo_bw.png b/packages/zarr-storage/docs/_static/logo_bw.png new file mode 100644 index 0000000000000000000000000000000000000000..df1979d3cc3317a36feaf5e7aab7c32998bdbfc7 GIT binary patch literal 45208 zcmYg%cQ{*b+eGtTnL*e6vTC-FKl8TMP3q9PdSl+!|iF&flimbbZ*^ zYjLm3OtsO3Cm=Roz?aI+ig5NVu7xT1#*POe; z>LRlF7c-xu?xONHe!xzzIJX2e#r0oPN!WG{Dr4GsMoE0}-h@DkNn!{_ItQoS%@SCe zj(KT98(@6!Mho;v;m=7+xrp{nDkY|A`barQ@1OK{w!plS6d*X+d2PHu<{=dnOntLD zZ>ot>OKeJfPb=te)b?09NA6AD6wsDe$-lNDGUfbWiC=rbZo9TFizHPvdn0G>JzBxX znK)~S0N>Jdz5lvY`~vAYpA56TtFx>>gH70?#$oQ*_cR!~R&WKfRPp@eVa|eIz3^yRCrJ?L`r$v3N1x1>0Htr*i1OfABST6AR|wv2)8# zHldDWR$@_lv%aUF)QML5NQ0?;hPx-h(nP5y22u5cR;U*lijWd1MLt(>qk6?7BFPH* z)JOt5Z7|&ko~oI3K?Lk(Pxw3?uhum(EkhFhfG_Ls!=qEi>}%VXVRnEGn|-&2Dwy)XJVt^Qf_1&!bND+^B`&-NMrWJ z=8j)D;@K>pX&YWz)D{dC=7sy#{+r0-e-Cq%9n0C{v*h~BgKmdv+2xWy*@qyb19y{J zyJ+)ShUP{#-JPdmgF#@s(N`(-?+<}}A}@HuGlmPI({^47ZJ?^=fG?=Qm8D<$FDkB? zxHRl&ACnuUgh=(8mSR(h6q}@~#HUYdiv7xX0|p{}pjteXj~zYqx;#{|2GyX4)9Q1irjg~^S(Zrf zA@eeMo0UwRK>tKY1r=|GcS1hDU?6O9ored=tOYI^9&^>32IlIZN?QGrilO&6Z(+QeDSDNxe26c%;|p(U6<{2^ zFFq&(PfgPzQ*n&1(u@9W*Dz+}3xi{}V4C`nQ4&bx9SK(gyQD1_Dk#5=DUx#Ih8)bPnbd`x2WM(2W6B zV&WpS{Vc)%p_E#WM++Nhl6ni-qAs%5uUwc4Y-`OI;Mvs_xi<@%17fXW(*@`3Xf_B7 zgQVO|9VCxI2WwlQ2n0BHH15O%!F2DPv)GY0#m8glr{fn$t!U1^b_BPdV7=NT$>r-L zL(*Q-=j(sOztt*yO9hrGRU(!J?re6h((z(|89iZmdf_XHGUJVz%n5^AwAROI-Aixi z>zi^Q53_FYT^ZIqh$ni0n94zLoQ0qgbfnb2Tm z9o3d_Y`S;WbcN5n{gt z5@mY=5dw$nz=NWJ4;Gyk(*>)Z`?{;E1nY+fZ_??3>~ft;xTYY#I-AidQHG{!x=UCe^hj)0 z%S>4Ot_I6QoeU%{qsss_m65YAgY?rbf4S#{m|fFIjDg3!ns_+dm5t)PolDc^`bv3J zB;^tqn6*~s$+{5OdFh%pHOQMu716{y!chZz zDDL|~kQ%j5$PRP-%dmlFgixn5O7nOS5!wk0eoJIYl3{Ns_YO{9s7QJauuy@qJ57f79eR!de?^guaj$=KTOf!7mN4h0Qz*gcd$8Hf2 z5WJ~sVLXt1F+#s4&n|GW#irlI+TIHrH|`9(MxASdzlFFka>=-uHaHjS`AC7fhost) zpodyK;hN4^wF-NU)wO!OJlqmgdAx3qvGr}JX`#rtH#e%j`WXBa`$9Ni($H~sRc#hw zZfW3Ph*$1oTH4UO^z8KleY_#gY&8*UFC3RHP!*a8XR5C$|I$Zft2mCO4n98`75t7(nJneB5{G(e9C|K-He> z)e9I0PF%x>)=qyV+}%_j-~Bn+ZS*FHrI8XxsPj@4uF>g}7^2I$@};ZjTcL~@YB!$3H5>YXAiA}R_C;VK7tS)Z{yIg4g%a+#`nWNoPZkz zVy20A#|#P2i7(Q66@RjGNIF1Mc}Eczn<bARW-wMLqnk&1bd}n5o8#ehJg!&k{BX zb!O9tYRJ%;_+iqeKDEnchg+hzwN`Ao^FLlsoIr)GR97C0BR86XBf0}vQXhX@DCxL2 zRKgqT=%~=BsI3a#anqkRMz! zzPVU?CrCLzBJ)SETN)M$k9)lqF%~0<=nD}+s=#XQE;Pi6hp=e~dj018*S|N}gYcYP z;_H1>cCTj*?p1m%02Cex`o6FH6?LgGQC%cu(yoQVNiYK*7ZE&X1g@#JcpRmsEfUz> zLhKCC$R}pvvb0l=yh>8dB9u}xdrqX5O_dDiSnAr4^0VH+2OpyQ22tCz(3OkZj(D}$3mYSOE-_I00=-gQ?3qM%6QS-KDJb3 zym7KQE|G|yVFjQ@M;@2?q!h4ZzSA!?ZHWgKSJcmI4TtAm4>^_x6CY}@Z#@Hm%U#`q zczf7k?B#4uZF}+8#W)J*`kPlX@q;8b^vk`q6v74)S#Buau^OZ=9`}6m%5;v|Kg@qy z?0Dk@<H_La2yzHNf9mJ4-D!6;udp)LBz;)ITWB%n!_?oM=^>j1~ z;RlCcwHa=gOA9r&4fjnXUJT%;sYcxB--b$;1y#W+t;BAy$jcGxuu5Opmu`p$) znnMsRqn#K%Lx*NfM|Dmh?oS2Qu47CExT|^1qK-G5=&HSAA_y6``3+~y@nSG93ljB9 z$HYPZAaC*(kO!*_JI+NW`n(_69?IR4G+opc72q6?OaHReUX**w%=-Lf_A63p5%+8< zrYqNgNJr3T53Dl+TfTs;-AqHew7s}F82dDG%R|^%-1ir?|B*ES=2-OZQc*Gm5}|0O z{%cE%Ju7&or6i!M4P-}tu56&y0pV9qVUI!!fM*;@udtkON?vBy+*1+MPFt60&lBG> zVFCk()`%k-N6=85eRA4UI5AQr@Lk&jPAmj3+Y?fu_jeZ2(P`S>wXe{T6cJ3Dt>_hX zTRhyb(4OFP8F&B!Vk-Xe#R7@^Rz>uFrAa0MK|wKLq*vM>4vTx#Qe0aG+AbcxBc}5@ z^l0icOfoat^`4C;AIxwTCI+Cye^tTf;l2di86$xVsZIA|RCKCXGS}f@ihUAnf0{j1 zRZt$lCN$@A5%QH*cSdD`G}CwImw~pQM?nc>aj9f8e-t=;~p{k6oe4fY7;01-%a-YqThe7=(!|Eq+_0 zo#yk4F)KM3;%ToND!JeXnYyooi;vMh`EBE#9a@ax&L@6tVS{=7jH;HXC<~M!Y!lQU z38a*whN?3RJ2dfsYH*%PcCf0!F`qzo=; zzJ}I|3LY*X3)FcdRO%sG-~^%ZFNR}p7fIT7sF90pCV20$(+mtj!l;I#mi;o+ z$j-B6F}zH1JOpvK2b!k9UAD@ns`hH&zIH_>*iET{`jGCIZ^H?ARK-n=U^g*+M)OU` z&5F$`@jm(NPOTA5qH-$oNEq&Wmn3c17%gy<_qF*#p&L!T1^(BpHhs0B(X zoM?_3m3Jen5Q^dSQ=Dkh$`R$q-M~74?4twA$+%hKFT<*>q?D7jEd=*=5L{~B(DAi5 z08hBh_ovT9WO*oXS%L%&pHPQNttXjZ`QR%@e!MVEv50t-9WL&b>LY@8)2aOxeR4XV zPTu=mu7nPpJWJya>=pLH{v z_V|*@Fd3=zx35@>;CK5{r`4xOsUsFKA+QE*F`Z@S(uOM#{x)m8A^W;Ziy~}4!JF>1 zls$9?XQ1=;eM^sXnpemMXu4~Pw31|!_&l-yD_x-@W9q#RU;FNCo)?eHz7W(bH3kKe zARV&lH?>blNNc0y)uIT)dEcdfBt5-iM%2B&dxJCNIABfO^i0MrpjV^&sw|l=n@#08Xo_8) zp3FY4!*9D!?*Q!~4Ynx4Z8fbbP_qZPMJpi-XPO4+&ND28XroP691Z)Y3CTdSb1p)n zzIpcSAriytiB109Y`oe1pP{FJ8~3FvQ>V}*?uqZDrWNXK&$PEVTHtg(qY?kU-)&(R zaxBB)E?o+z=vZD+>3Oa6#S;PltB9iRAj2sZc&4>ng4N~QVzNTrTKEL(cej6uBB;L8 za*jkbKRz7iNWy$!0(O9!tdRtb3;h#8>-X{5LW%8nn^yQOYHf_<7evN8>1Wih^p~1d z)!wqE-Y#B;M@#?kR8GEn08jDMGjM>hv?RcexrjQbjvLRs7X3KAB3aSndh9g8sP{5UlF7$48Neq(bRZt z$;SPj(g?}7W$}S&IP=VA`+&@bDlL_yH<^o2r^P@On>})ij|$hMbk`sym>aTmBU>Pa z5fd-s`)Y18hO@+TKOez&_CR;WDSb}do37+fL}&?TAF$uDpR^~f{_c?3WqmC2-9>kr zTv@ue&eT))lou*oSp7$Ar1@MiH|$Fd=o3fOu%}?6Kk3~&qE(}I<$2tY*KjxJ!j+Lv zzRNTvif2m*P@QJExB3&G&^hV-HTo9U);Q`06^e59%z6dpLNI_7=z4jraF5EE=j{3R zVtN8o4o%{-_w3xmn-pcK#Lu<3w#3ObXe-_S;uT}~YsAavl2;_m;QnYAE!AV;WGBzw zhrTV1a?|i)BaaqNuzd!7T638PT@Sta8ET zYa}}d7U8kaG|MuKm>l?xX>0UBp0#P4t8aW`-VwcD=@25>mTr|Sj_yxON1j=0SSnrq zle-A#;F5;9>stx)O89Qck=3u475xr*XK0D|HS{Of8}tE1MS6z&b|mI$=n1HV=J*E~ zdQP`(=9UcX#&r$TUr&VtF8dFg^H_XsSJeV-{b(^)nYu<%(*H~1`}*0{a~o8$>KRK@ z7k+Q+WJPi39Y05j2#w#3y;lhRF+FF$<*=8Q>>sT49L5&}U0G5@82*0L6OpJKN?s939;z!pAP%e_)UZvx<5AL}oE5Ca zcTH#PNg>*_7fpwc5KGtFDNR(VP~BAiOs6zT+XCy?-@ovS&Fr-s;vrtjnPJz4k+O#vJygFrs~b`&ckrVg87+2MxazWQo?2 z8vpDk{|tP0#rfGy!FSA$s~Qqmdx?Lk#|~LceyC7j$#YRTh6={;%JK~Q-|O3tBnlAM7)m6eFtJLw*$CG(ijPJuSeeyHVh za%GZZkSb?8-TE>KhjM73Ls#X(Go!Wbqa^#gUdE&SxPmi}Rh!@cZ?Gq3e@Wo%yV@COJ4Lmk_`Uc`K*dW9F zLFfBJuA*DZqPjmRD+`Zo7!{}3QF__%e6fA5F;0lVtRB8ymta8$)n4?QT^J@ofw(yu zbg;A)`Aj%^Ihh57ki&(Yk!|2_3k%1AZmNVAGhJ|CbcPsdcw-*vWlVUB2U3L!;h4$` za>@#D;%vL5^k_9k!`O1!(AQ@AL7Eaps1h}{VyFBZO10}xa(->QXvaQ$B+|<%r-h$_ z58ffm6EuXu%Zdn|9N5^6;>zO~n&h5`M&ix!dVFJazz8kzH9cZ(A4-T{mkr%`2{E&L zFXF^}J&??+ZT??Vg7zFMpe@xVjPjkennly)Z(0v#Il-jiQTS z`P#L=8P`2e@}gY}A7u;%_>LKBcuwc=QE_Hirh_D5n&l39EMk@Rr&p5%&6H(cTtb!P zeY=TJK9h6DW(LQ1hlt^FS-+#GAo{tIYh?J%Uy`Qm(^!tW%c`%&5t;PkJc&GL(}$k# zSrD&34YlxpQ-6kgsLgeHuVlqAFXUo<4Y6j_vg^ z;IO6re~kTJJws$tW6lKW$6*drlONK1L|R&#RE|89% zNw&XQS3b*#9AYz^m9M#5)S~tnyya>Z79e%5g}=E|W)$EwORcnmvCYN}WtQw(-wfJW z+wR{?drlWbMIbDUlLlu}F}Bb4y`wM0N^)md>ddJR79|+ba&`}di3Q5|-a?i`*Zmhu zzJ4dw?tiu~6u`dk=>!;A8!(X4L0oxVeO#x+_x(^R#Vh4dH?o!;4pk>HGT!kfdZ-S% zHgq8V)x(zV;LP~;U(Sb!#u!LdEdyF4owuS(cb1+GnuPrecQ&~lIlKn!-L1v1hRU>D$#)|7Q%b2wA z34T$aG3=ALbq9U9M_@fg@A#Wz&mT;nEwXRzDPiMo^1x{ZxZ_Dq*aK|yn5<0M2Mytq z`Onbkk7Zv)jE19x+;8MvI&8%{!UJ5wS05l6KW~4XaKKGE)KfBv&Wv#nKVzJKq&1e8 zc@Fe7t`_%QtEnSW^L;JcPK+-Q?e={CnaYMVq*XSkDMS$6%zLX>>R^0(>uFxq)-5WS z`CnTaBL5531R+P`+kXn0?B+k*Nbwo2VtF^2Z4-jv(EdL!z|>8txGto|!uCw!2QX{{ z|1u+3aLc$%d9fQko8ILT^dzjP`eWb7{(&V$X~np2`wsQ4Dn+&4a6;CRBjmbO#r*2V zU(>SCN9fU>D9UB;#+8D}!YJv5W{@mE0u`AzJ zr{A2q7;}6w;BYq!Rp4rR1{NRyK*N5g;Wtfr!@T~UqY!$@SG(u-q{_j_m#xy7Ngr4w z+DB@n%$vF1ZFX@r#zzVAb4Z>cm{!Z5f28?GHL6I(V@$q|evov(~WFXzDf{lwUyGRas6e(zbjO{bdtr4`%doBjX&~}`8brEixhS!?w(lRAk=Y#OpWo+al=+e7DFnAmrZd ziu5rm7om_YvqkGkfq-H$b#>2^ZTqVhddHUlBXIV&4k2 z_BeK(p0~!e5GzIm0~6%50QBSQ#i`OW$FtG0i0+ly53_W#Q=t$J9%H$zRPQJ>JR@K|T-3Dm;~gO3(GT;p zcda&lw<$63$|SnBmG~>9VuipQs@cJ1&p3miyuu8#>Z4asm6^;0$dS4yAle6*=}IG7Io6(T3Bltx-_vGr>1zkZ?=`hYOLplFlops^JT*u zE3%kVNnc%%UGk8tfbHEWpcZsNmuvmaaWRJMb1%8?p0BVVunL50N(>#72YEt<=$Ac9 z7``&edkud;C#@h}4&-BlEFi6C6>rlBW&#d0&wvCg&KW}9Cd6}gpa{iAeYd^BZs>%8 z)e5=x0h#rP_mbs`1&~0K-|X<_wR;#Qce9%;K7qxqLpi_i8@;v}az%~LcB1Jc*bKOB zVA_XYNZTlN-9>?k*q_BsL_hyJ{c83`herf>fPL-+=WV1SFH!qArZ*mvR3bB2j27>^ zW>eOsjlC%CO~w^$N0}lQ1-VGipT+FNK4Pc1OaiKR)65?Dn_5f}(@7e@_4h`!K;+#k zoUIW6zcv=5L_ScWq}HOw5>kE0YSJt%WdcTaeQOL*2bMe~ij1(-cf;NJJ3V$|AqU9g zN7(GNrgzi?e(cISYQY;g<=uker#OF=-}JCj@1S1is8XySyvFs}Jfje}VmPZujgs!W zj|K~~Sj+w8Hfm?8YMj|)YB6i3u!iNS6`LN)_NPUl--p%{fB1LPkIio$>6Fm@`PPz3 zh-Xzfd6AbtSDdT#CMXrdU2H*Gtk-rr04CS-b+Lwt%l*ws%V z_%&jiEHD53a6XLBc%VyBgr1P)84^>ra>6V=93|GivN^>0D+Vgj5hI)qa~ING3M9PX zkWFbt=YGTDRuu?Z+bTohlxr8~hHaG@ zptWVH>%|R6^>J^BQfS=70s3IY6xq2xJ|YBYD+YMFXLXGvUhSvhnMD5IUc=Xoj<01M zlN?KsH|=++M*ZRd9s4I(6GIZNEIdP4YKmV`f89uZm_`%@%mM0VKOdewQlJWB2I}vp z^bM9BX+X+dX3DN@^)EIaa55`z8_EyAMb1XtxsO_(H;(?Jgxs5s*I;Sshkj)%v)a4s zEsqPnbg^s{@jQV=l}t0J@ga19iu%x3oV zEwMD9``rJiBH)dKp1ZoUQ#$@$J;#TO4g{d2DupUT-e{5mNJ zZaTplIBvWLg!Li8Yw03JD$4)Gb;>R-uHnK9W<=(TFArz)zFY-_)2oC4#g%--%e4B> zk?v@_oO=~kXrCxi;e)U0h>>IW@4qA@)L~2&pf3jJRJ?`{*qc`59fKUUmwigIFSagP z;|GC9gzP)gE-B@!{-%^c8HIEa_OB# z2^S1kf^I)TXCxVc&!YZ@F6QsZE37+suMEwvUV!G^@cye7`((9n?9GN`!O&al`$WZH z=K5RNlwv^<2tS0gFqNjsX3;xHL7YgRW0-JuKJp#^iesT+Rn9IVWGZp)ln$M@VGRpE z_HnC?U-&SOy#Pf#x1(|0{Cq^u5rSnyYwcaVOSDKlO5_Iw2>ai2)c?N#K|V6h0S$@7 z{;_}feXgAn%As2<^E%;?D~%E9M|3OA#n)%UvuT&dA8kMK(JfAYs>tyNm+gU1GWs1@ z-L286$MHTjg>S7#MX}A5X0xVQ9s^bvq*kgLZ%^%i;g)b6wG^#g)HKOPt`wQm0lt~K zz3@Hpv4#ElsUec`HI=Gqf0tqIKb3+vIn#vJX{vIz`&^biiE8u{8SM5%-KFXkB2#tS z4OY7k2@Xo9Fk6PibedKktbGXQHl>v>YO0XE3cbF&4ZXd~_v)m@hrf1A2GBgbL0LYT zf7?2!rl%EXtk+Bulz#b|oG>oiIZcq>o6d-W)}5YNR_5w*8n;DGwsf`v>X(SsBp5gFu7~)$?VOhKmw~N}WW2nqMzb`>29x zu|9ue-mqHbdUmZJdb0#Ao|V}_WNhiCEzqrf{tR0KX!Vk-Ck(LR1fab5CNd-%beWqW zbw$Gp<N08)T3_LE>piK(P190EMzE z_9N{R^c|LzPVUicH$vmPk@>+Q#jG%)?2DZPZB)}=NEiJVp93^L0AS}nhHv_8AH*aL z6BhbN=>Si9XwZ=Y{<7`xkAy0@GrnsfCMefDvVpYno5>keefr%~gE_4Ml!g1gB#M0r zjKWdEHsYeoq0Myc{Pfi6-6ugFswqQmlXE4m!d}Ux6|2AboN{bTIWLs1E5GFk+Ax~5(QEgA<}OpSLgmHC_bs}H`7!WPcD~_=}Kqs z6}uitr_c(NP~SGPaegNyh>H8BUhr}r-eJ$WOR^{Msx+sG|6xX5j7j*mJ2d_Qnv(7} zed_oG6fG2(z};}W_Ck60=TW{$Xz#W-Ml^)X-Z4-tYUV?8+xokf>8AoL9WUxUuR3_~1KDPZVPK4UO>N zPceZTX z<{v2A<&EjCYl@N5g_fw|mnrhXHo3;rZIwigw+Y`#b{3 zQan_tfIMIwz3x;q!pN0R%4ntN_AbUrEZ@x&@VyDlv3==u1r_nfvX>aH2}|+z=Qm{U zEkg{fAd&i2y7E#rm)`*B>yu5_ia+TDygViKk@+Tr2l(vJp+%;jrKn$AyuRsu(|H*; zUSn!j;r!Xc7d$sEW`)u32xld@=ym%6{P$=@Vp_dFoAf;@gbYoLB8O%<<$SE{>*=5m z?pAp;wz$PEcgZmGH)o|({({8MxipVAl(%1OLH#OIw-jgOCbDbu7lr@)t!faL)!_w9 zyZ7L;F5QN09!yqim2`H|>zf8R^EPb@foA*Jv)t0dKhZLB^0(MqzmW2v?PPKXu6gv$JLPi5_0E0S)R^>iUiI(?=%>5PB-tI z-;pojANiUQ;NLGYk;RhYAG z8|a>BT1lWt@`Fxowz;%nXm-tgpt|1~xEa4lQnub_DXI*a7Dp%yDY?TNIO};W?gw*1 zJj7Tm0U-!I@OBu~Du!cKFedZ2bV}ShxLqQJsK_*s3YF|96t4Jd{>Wb$s;gF6xwE!svaa@)d-$$&@=F(3<(~vP$s&RV zR5t6T0A;?cG1upDqW z`A^)J3wDtimQ7r}wxeY6_}B~#V*gK=w8n{`qo0!q%kApMR(s3K>w$ z;+*{DY`lFcy5@2KpK`}$kl2i-{HECyLyOP7=@@ZG2=>RYbeLX8FRksnc~y3#(t#7^ z9slQwu3Lu6{mIe3&5rIV9|g!e)AW1PeHmLJ2hNjI5)%26bP(*e-2vS?e)hrY@0ftuGXoWuxOXleP;NJ5H}Wbz>2~Rzc@IxG zUPrz3dfKp`5lbz5RsIiOz7}mAdz?w7_i!jX%{OKiT(>>Kyy+{K?0pLN@{hprW^O&& z_RshF(e*&kkh`#43{qi+LljSV~yA;Exdmd9i=NicDPz|VB#^l!L zW*$9So8hA>TD0dN-%6#57emQdT?NkKN&&d?)Pz)~jTfC%@)GLxyzLH`#j#DTDME|| zqrC^5!rgzJc3b?90`!vb&`GX^>=W-N48$+fX7HgCf`lj~2FXF*>9oyV07_6Nedp>% z4@QCk(B-GKbUt}{K_GUzSdhEC)8cbc4ip%kH$!c$$6}1lXRp9IMu1>d9W3Xwh$hdq zd%?d2vB__qDKnGQ$t(0>)6|;?iVn>^L($*X}&ej@Xq9%!hQd|?%FDPN*lw?M5ZT`@E#h}hn4}g+l*4GT@w=3J z*|iZ8vSl%uHH56gcrYMy#lWRDHL@7oF_o{jZFcA{Bd|~PEiD5av7FYz)(kiX*?Xk> zIO2q}2gmwm&JA>o>_PHU-*?q*T+4D#Z zTR=K-i=nmf3!$xN8FgI&9)@3Uz&^t;$9F|CyUiDGq{D!PX5SPQXrj`$Js&K#t!Mlu@M%~lcKBXIZ?yWj9f~S`LA)66pW?dKuCnO&P}@F!!{qT& zfcuUUZk^8yxmdGO9Q40e1+2UsE7$oD)+XxKKU4>;#jbZ|Kw^#0?KF?iw7lZL^#}dC z#_|Nh-u3-fpMcdyw2Z}%gYj?a!A&fp7@_r30!Mdx-fDr#zJl^CZf%_o+pkP^8`acc#a2Tv{rw&bPRGV?yMz3@Pfns*cq|N?DyBBqk3d6iw0~*w9JN*Ljnn zudkWj4#~9WiEgKa-~Z@*YEdOUJ#TdTn-;Crn8x~dn}f_N`;Uu1$$!(NozYnT6HY%& zeyf~dk6MDls&1!qAJj8u)mUu51qyKHN6zC$zEU()119X6onK#|!#>h{@jM&N122?3 z)V@>?mUVfjpZ-;d^G{UKx9z*=xzk>hK*Rv`*R81vW4?=DiNoMq*EqGg3djeFbP%nr zTxGu-D}ar@sbPC}pJIXV$1+3SA=}J;*X@=h6oNSpelpks2aH*mpi{{@U*mq;=a|TJ z7Q3FC>J%7L*8?`?@abPyoq;2=uqbqg(Da+U$qxWXUFz!Lv zsWu>0`-hwKUkVdx&SPw~)4OADAsAGi+GIY#*!1$-GndnzG=b!;KH`Buaz)=-6raXDG)?3Z}UguRB3!*bcACC zD)FYxmf3C32^Cl144`t)B-Vodn7XC%70H;<28}T9M#CPh4)@WDR!tAD?5uoTEB~o3 zQvf8y!PbvavJ~=A9-;VRxeVt&rM~#}%86IB#-D})pgvLQx*rR7bZxce(5m^h$-3sb zJ}mEmq-}Q6>?~BX3#t)LW_dFY^)xA2F^aIk%?FeTP`lf-UmPuLnvD9U31WtD&iqZA zFb->&Yk9shm_b)J2E?S$!$v#x1lr3xS^>@u2HZ*Hw{igI|J=A1u}`&pftz&zKpa6^ zCzl}Avpq4Z*Z+;mm3^yZ3asd?o-k>q@qx>fRK zd$ivr$oSE626me^Ge8&e-l7j{kh1;G);5QcS}Dz)(e0MI?YuKv^@~I)a^&d^$U8lL zU@6x&gPs4Fp>C&BDn_rSvoA#{s}bVu?8iX=vRqV&&W1i>V4tU_T0Z_mkVUz(A%7hq z=-;gnnCBs7zaT>}oNuUOUjB|BJtS7!fO@iDy}jc7!H6X6jeV~vxM<&-> zQW3(YgX$vjE3T>x3MV&MXUR6CbV;|Kb*U`IWqoIKvnYA9Lk!&7rFUzJcM&zCt;4ec z9fihem(TTyS6P)Bepif;28x+QU$Tok`KSE2fTB!02WRWl)07Ly`0S?OF!@QmCce;>>z`rT08@qn7Zp|R<(2%HU)R0YU$SO0G9s%UFBL#F)xm4gb`Xt~-N zKAi$`!KIQrQIqOU<;y^?2X_#$!#zpi@jTv;rtN$a!I;RxhfuApxm2CSXqINC(nOYk z?c3zj%@390AFn;C(EJh_=n=yV$Qi>`rUAO`zm%I4S~rxf+bSDa#wq~!J@SQ7NA}GI zDaXI_&%uL9Ni7Lm<2l%D1H(vfXrAHX>z1@R`Mx`$41@@|_vaM%Z<7jJS_P9Ecqeu+ zlZIqbf;uW#enA`iz$|lLK3l&aUNS3(bxl#yHvoB7J_3s$5>#uaUY1r%O72^G`<}tv zH0p~ZYG&_V%k~gZIEc&seqbD4gNU85Yxe9HfFG!?MGXP3nuO{WU0)Q~l@Y#$soeIWz4`@sBNdkT zOE~={?175ogrJDK*T(F^3@J|PY83!inK!7A;xgH-+*O`R7lSX6U@_0`3FHISa% zpRXCyoznl0n?*Dr;lb*(O4^t2d17nk$Oqr%bC#)|P?1_XLnbzr$+9=JtS`qd;99eX-(|`|T#c$Q6iTcO^Eh7&HXcnvedsUtDD&N=Q!b_~PpG$&~-!{NHF z?tDmnX#5&Lp*HgL2h7mKmuXpF60o^m=rPmF(b7NMzb*DIc zM6EF*4}W`jT^ILX)Wo`P8MF7AVDyj<8bp4Nn4ps1UL0C{Y(}$H;`DZ0{)>Sz63Of? z40OYytCG3M+*UntbBlL&I>h}Y%d)%^LXmWG=W4x-<@h; zIl#bf(Yb1D4RJZdgIA@UhogOJMTSR&N5y)c?8B`W`Sobg`sQytBY~7+4oln}k6+Oc zOlz<;q8<6hsVVQ!4nr~1*9tr7#z3!R90+UQROAh9CB8y%A2B1$TOOy>D>r=0yVRzw zyv#+&5V3T8in@Qo%2f=01+OXq@`){?(P3gUY8L^T@qaVWv?6(^)OLq-qZ|A5O`W!l z$UB5}ue6FM$$xp%!5{-`{Q~ zVhO}Ci|dAMHIuqm)5=%G=k6$`e=e}oYF!Xn1VU3ugIwfd1S`h_W z>v_j4d^FsRocjPSIV`LG@>7{X1uNxBn<;1Y1SAdfN}Gtx<2sk-L{(j55XYw@w^rq{ zm7sb40&7E@=2!5`uzJcX;v+`*+vT25h@L}j;I_uW!^@^?y1*a}He7 zol#;T?+qW=i)Vjy4O)^vuF=n2$Pz*=dg@j7|0J;qG$#tU8`fd0*4E1@ERff)LJ4OX z=>6Z>8*^1?!!s9oNOkCZ2a{*qe8)bY*~R=9?4MU_6{CY%0Ps=ub@HF>LqS^zS9I=H z&_6t)IxePRCNuj!g{SI2{lU1*P~eKQgkR=#VHe^Oc&Q1IW2VNlC}i7j#Odk5wk`Dk zX!^>ysGc`ox@+kMmy!mh8(EM>V(FCb?nZ>AO97=DmRhfY%z8x8n`Q#BO+d1 zT${EOU5Oi%Bu~Gx7A<-?`&Rw{5XcJ)mOu2Q1@tPwP8mf7nssh%#C+17Z~%5gV>1TJ z@-H8XWEWRZTEhu|I}?6Oj)|AD>^$Ln<={#U2vfLFL7uUdo=;l2h9-ESQ>mdb=sKGl zxrXMb0?bRFGlT}q2LppR!?TMh!}0E;=|foiI#q_LzCnyFEQybZq-ra^gOrmbCZ~}4 zt4^QU!6w_1EGBIOA$oq8FkO@*;|UD<1wnMyp@kU7IuV| zb`gqLO}oTApfCxaMrF3xaIasZV8#gAp7YPBrFSgzm41yZr(%F@*kx>ciR&n_Y$0xgg z>HpgkbB~@BMOsmA`*G(B@x8m)zwa9y?i5zDnwj?H_Bf>?Jl<^gn23*|kO4*A% z5k{@AXJL8t@pdm@nC_8_SA_hcuqLnD6c%1*kJXc9xp#O!SV#}mMBd+hEZ1XaUWzF2 zdh%14BjqSycaC`d<0h>1{p~LhbiXs~N0*btT+cZ^NelVRjhmW=gr4iutMZ@BXhb+F z8n-!mm;=mKwee;&pIR7eNy>i9aqIoJ%6GAz0jJPVT7_1w>90pgl#M4dhrwJxh(T-6 zLud8oa7A|Tfa%1fD2DV6AX_$XU!C#QaHt$hpJQ?XD8@R} z+PK%v%kY3fsgSC^*A;^>Y42O#>XQ)uM7&f~SPuUC;-=U)&~{8D!J3DApck2hiATH` z0^G0%qH@aw!&ELZQSSeH$pHVwI$4;x{$0y;G6g>rpa%WCl-KoAwl3o_1sQ%~e_Qi+ zA&TX=f~@<>ZhG(cBOY`^~;^q2jA?A;oRYI)R!X%oAqJZS)Ya`T1=psD>dpxXTy zYS2BsXC&!caTgMOyKSQjO1EfSMdTkcsMv+uZ~xj_d+Y|Kum8;ik3z=Rs;ho|cDHAZ zIgIPUih!_O%FcJHm_V#4MHiMKHJ=^%47xNN zKcq~9gx=E=*n>27lki^!B`&;R>xg{z)+;23z$SvTV?YQv&eS48#nD8g7XHQO4xwGt zr&8`%qzrX0u?FUj`W6ayM7Cdep7Z^>>du9n_&tju#lxuHm0NyqOmbzH{yY<}oA>L| z=i{8qn|dc;XZA`9;&Q$pMbL>rUJPyc)?lDTBQrWB5~DOT``TLkx`>$ieFe0AOOj6! z@q32bj}5HWsyXi0!9`XZ_sQojhuxe{f5M(o4+Ax>JesPRmFAhxtMc+*FNDt{vb?_Y zspCV6^AKS~T~pdI3#lb~t{HuZOW){drkWGEnhq*OtRl1=ilgG%6C3?k(NOWl=ZSca zO2mC8rPsGqeG-uwATM!PcuJ^oM&edry>GuJ#_qU|I1MwzoX@Ia1QliJdd}DFktr})sfStrkrK7TS zDxil@UJolQzyd|bOj7!y)FLmX4%*Y}#n|ZkE54FtAxD7N)o;sej^^LpU$a7j3vIyH zPXaLVKC(uxwHy=o5!%dd>w@dI>c{6_5?HU-!M+0nr+yZ@eCm{V{jVn=#iPEDLVaVK z<%V7ZNR2$e=b;BWb`(i(S?E0V|I^<)z-7jpP^@u^JCDMAt|(c-O{G&08cM(G$lf-s zD}p`+x`*`~7+nyZ4u9&yV+i#YoUDpO)C}s}1~(|i9dMjQGuK8@~Qc})_)cwu)qG$881hn2={%|r`PZ9?weB#zB)en=?46#QNUpF z?uYl$(P7t5)b&z*9*f^z+2PEMnF^NZv5i{kT(C>QN&lY$uAkS5oKYrGjbx>wm&fh|YP_BQTddky z|B-)kFctZkyLBkyR4PL(L~&))5jbvP`+94`uTX$^{tu&HM9lLG#vf@1qRFVp|6QJhBnd9c%uNlPzy^Z zplj*IVOJx{Pp~EcE4KJOVnbLKrTzPjM9}Sm7xcTkI@IeE!th^j}A+v`Y%dfC(le)7wuWpzwtWps~Tmby|BRmXj-gasdD+Z z^Bk%X8QPCTCJ>BJxjzl5SwD||2g#{1wf+Mx#oSR?@oB$3d#Y&ges16(URacsp zuPy5k0 z%KWQ{tFUNPCufl+*;m~UJ#0>>ruW{X7I&TZ+GqJ$2|=SyKqa8k&#$hIB-nGY**Bt3kj5Ly}tYvSg zgPJ^`QkHca@dn;X;W(;tNO zG9^0(t$OED13ONeORt*Df#96~i`i!?3u6bK>N{PCCJC>Ea?!hx4V5of2CE3NcYjL0 z@@xsK(P)^;(fC;sE`4%(_~CqIA>tO9uj+39_G1hEFOu#TG`L+8SDYZ}{F*`ki6hb0 zigvM}+8nuC8Qsdw8uhH{+frG{$d@ArE%lbSPBg+vertyy>$a-jSKlcc#n-FS9I#+- z;Icc|{4NDA2{CBqh(FNcrRfAL^qln6eA^dTRZ%wmo8fWHmdE#9X)2)Bl||)hJ}x+c zD)2EMff)~|jY-41o+1!=7T)?Tn_0Y|tX3kNE8*vb+cnqkl%jk2Py|!JYu$&_8T{BE zp%mB{s)8}Bc(E+XuqfjYBY zcP8)cT$BmJ&p3{aH;&7?G8V@;aANRtqy46L^f*5$5 zHc}V4Ya3OjPL$4OB4~V&qyEqQlpa-zb!sLAIIXMmG8H4d#y&71vz;z(1YdrWpm*3z zOQ$Au3Dm;U?v@AcH3LNoe}%ivWIK2sP+1AJXB}gPI;%E3 z#SZ=!ntwAcYpqrGw`;WCGv=Vqe7IZhAUUzEX5jt4ah{a>*&+4MilAQ6iwc1ztN4dy zsfq`2p_!8O3ReL)QQ7EBbVaY@`z7EnCL)+N{s5SqejUM0M~1Z+D%Of${suk$kd@T; zi6uyZOjLsC{PD(f^!5%1iyOuK+o23uO^*>6LvFLOc-d?fCf&Q83*mNsJh{_Pc1Vh% z_q!^3&28B=ou~a=mpr+!WG?kbD)RxfN;$ll0an{0>QTdDn*v8$kp`B`X=NGGzmY@b z6+0sMT~aU40oF-zSwi1NuVL7r@j1~cd0QepPHV9SncE^lVd6>*86wQxiNQ~U8BUuPCzHRGTxNlEIj)D-?QqPdaCc$J% z=7IF|{yS5mq|}0?@`r<{lrs-$#9c0C3(ZJYknyPXJ`R0l>!9D*FVXFZ+#0H+Y2t%0 z+8j#aq~880cAFKsh1K)844B^okuiHb;v<7Fv5M@CFQ0q+bzIU>u$irkppN!{-{>Ra z+Z&vz_@<4%qvLJFLgqYSg4h>dK;ws!r!I8GVK^|`8fuc+=%FqcHJG&;2}DMU*CGP` zyJ9Gu`y<&g_(HDTY;oQgrcnlp*l;S8d@oWNA)PYXl}I`HuT$}7dx(h;_*?WsW9RT0 zmag_4j(<4Y?z%^QQ{<)w-MMRJK8?d*IA9eX%V%+pIhNtIQ;5fxTVmDq@M3^bOW+$ zteGX^ZL-wM?*1Ov@wYg=l`iXSC~`d99;>--m#P~Pea1B!%soc)h4VCl_Bo>x4GH!| zI+UDn@3yRGv)eP@ugrJ&rVe!?-7ep#L4{5hZBqQ3$r~A>7QtYF--J@mc|;27iN)-r zV=OoWAF1#hI>#zxas_{JihU!-ns4gmEmFTzeK*iEAs6Cmu(=|lV^oNwU$frg-yNOV z;k@?efCVtK=rs~l4$FVuJFdIV$_(gL?u$%A2K5#oR?6kjADQ66T<#7-u4Wgh?+*EwJ{caM5wpaf$)JwZ_a(|pzMR@1(QF4YN|7Cnn$CHik#WILK z6~{l22umL}(c*CzZNGKijQ~y@tbUSd) z-O=J9r2!S9QmW4Dgst&9{s_X|+WamR9Inv!d`bNu?dP5rImjtX;0H0f7KYeMO|8%w zrk`C#28g@zYSKLOBI?(F8O5Swqqb7+vtR|kgR!OWcv2zk(GRND zhD{f=f0#sX?NMX;+RlBd3kxP$qVjFA_?hxfrCfSm2yVFE!>vDLASPedB|gtDV!h!~ z_E;f=X=A)OOLup#hDc^3!RNQuA-X~jxBE-wKmN#hvc8k% zt?ciTgPvPLN||RUAZ61F)nz36ca@z|cuuM&emtO&=v~CAu+{O$nHihm z?X#KhoEgn%L+<4|g|61TKOELZ?a^bTqwDpLZ8*qzdRq^gF@{o@NEW`U{lPV(8o>Os zvRltG(s%dLi3F`9<5kg$vYC7$vH+wK^>u;Sroa=$mYv;+NTFXbS35&U*4gs8h~bf1|?I3SjE!v}THL{LZXNfCU#IWjFoN#DydcE(KGotU+_2#ppDXg{_}}^2cIvUnc*8%#|GxRox9>&J2&*EYIlvr5YGr{zG-SU}xqYn)DQCn8dm<<1trGHMa z>rs-GH%ynJFL^L1qYn+!$~w|_^^smVS3TA#2uTeWGsR%Xy}x|O$_Gk@f`tMnH1cG& zod0@fz@H`U@|3TX*>s$z4m7VDR%CgG@()7cy>-wF)nlT8fj2?%HUmfEqzV^?_&j07(W7 zybi)PEMOny(d{d?a5{>IuoP(OYRtrhzDDhm{IQVD!Fm;I*Xj(&q_M;j~W!PG6?mJ0bb0TGgR? z9zJ&g<$f%QW{2j{M_>At&b@s|sdqm)-nm*!t-iT3f+JombTKqCCbRX4%%c~*_Bc^F_bkxc!Y4COHaSXrqt{Se zZG`)B>cXF#_+=3@u#a>7#?X~l-5*bHgYG}z;DPKcI#$Ec=FvM$pNF9x7E6+^C5^k~ z(({yC^_hYNzr8`^=VB^K91H5hdAsXh)=DUJGV1Gxk-l`=I8rtF>4R9Sf%brMJa{;O zRe_s-LTGQaIwzNZFhv@JPXep%BtAuIB#iHaF9pC4GJ66~VwGauWAcb+Kp*b*5RWz< z9@D}vx1HdBW$ZgwGjAeLeTgvl+mFA}fX&5_{3wphTj9zie!VlCm@mp8G0Kcc8{~BB z`Z2rP2<7Au^ww{BJpnG>XxmzEvSX(ic%&>0<2E<&?}k1ym$|P2T2|KufkqIvD$*V6 zshKAhpidRVZFX}*j2hfWpVa(>L#+^K);Z~oSc|P0Eo6IEwORRG;J2~Cr6G77>--`w zMiwC*mu`GA$+IzREed|Ht(NzXg=0pqJ=#wxdtr-4?A1I*LGH19O{9~3vQ`~4P-i#; zn-d_(qeLFgR}I&~f{F0;%@XsZisA7Vd1qvvY;(2eS|BX&Z`Rx8h(>?LF8h+g{7Puf z+vAxY%meH4BLp^Ltz1QWfTO*q%Mj!N$VegF_ha|SIX9a6^T0HfvF!m^=9EBKf*;8D zJmk@nF1xHi{pO&ec@Wt14V+l`Oa0|!FJ=%)lD35jII=c1$Q<?JRK6I2=W-|l^4^J9J$jIEQ8{{wNv|*c*}3?=-D|_qvLB`d$G14 z4t&8f>Om!UZe^=GB5i|qT@1Nb1{rGAl%AAA^}&~mxg}==d_n+J8IBj63r-c^i%uz@ za{{_7L1NE~C;fj1NJf4=#Iz0vf#kS>wLQMaZ{RaF+b7{uf5HL*I~Q6z9M7wG#$P{c zsD{#ntk*&KSb<}4)dRV2;oG^$4Rv@vX^SkDPaIblvdw7$ z{KY1}8*<d!6{O}t5pfnx6_F+ZM zD%!%}@`%Vkf|!t&z&^n3i@YU>8e+J4hn9z?0~zN4HoJAWU%!zdKAZ>oq(Z`gBY%1s zD^t7lKtJ6KO%z{XZKDNif+E;}MObg(uHeg-+!PlQ;Nl9ff=FR&;wVQSZUsf!p#eUb zfk;NswrIaq$>HzHYA&`XLmwAHUnY#Z0h?(Y#w3_D%*9@+>!2$71qjrivU~T$J0T|f zVG*{z9Fd!G5;kSLziX76I6E0BoUhVYj#MA-9oLP(%wYXV zjAyS9Z1^d5mRFz_8effMKvh)|xA?^!%~#0pkgUSL&%DtABw^tK(! zoN{@Zvs5mx4brB}z{YG_B*(Ro`qE%bX5tE~Nf%4j66=zGTWRkz2;ZjCu(pZLK?d=0&}S?H2{@$9ZW$ zxjAHLpYxW*%EX@j=h#Q^B`)+f?3?6yqAGRHZ}aFue)6lYhI2HTk6~lB-t0YZdEVE; z3?@?S++70mX41nyTCz=J?%n@E6xARLP!&p^N2zqv1(iz==!f=~s_{e*yu~?iRJLOQ ze6j!!!>_q>zuD(Q@_|6Yz||QUW$@-3xKh(~1ard50WIK@4p?4OH&m7zI8gaB-7>ct z2?EOkLZ`WG+Y6e81ROs@AE}M$7=~ScB~M>C>*k9_o0|VF_bsF>iMvht`dp-c_?CqL zIiA!jC*VET#l3`P&eM%sCgPD0ky9b3jC6Nkt)OMP1$M) zsl!Mk=W5~jjO}$_?QML#iT#fxS=0VMp4JC5r!Vyy29pQnb>WLPakqA%n&Cdrr~@nw zKgCsOTk3)Xjo>uaaXH_98h?(NR9n=|QKmfDrib3j5|`SI#MFC?=$%YcSablzGQN*% z%qix5`frCZvgVR{=f^Nfk&8Q_N(A%35IZO@P|!Aj_w@9Nf%6}JnGNaa!wjhOUl{bz zID}nfQs>MW82I->kCW-9JikDU3IQ1wAUnf)i}0t<t!kGlj5Ds`AQtsSKVO3GgWlY3>OB)|J13793~IGD<;raI%_OJQN<5 z!T#N&qoPPUMry;D?|0KY{9G0!xtAwX_E6^fx;=QkcM0k7Dl0+;D~v+JDS)b=f<}k; z8bj&a^qEWZ+i+PIM0&D++sj7W+L5^2x!<#H}cKN-!>hYlcf*wzgi)pIo_a@yzKh;v_$W~&sbv!jfFsdH8 z;Wl^NXY8^KZ(`CmM0>+mvi2=l%Vp@noTANFdT3`wIo!DydofFMifuiZ2~+Whit4KI znDXKDCno)|pqvv)-yp*-z`V6I*38;9dB)0Q!8sGT|J3Oq2Hjl|uM%DR-2+woYHjHB zQq1iew-RBx)mc$?)O7mRq6S~;zyWF2A**-3PHcRAXfgYPn?jdrVWiL0lr1Za6ukKV zE`JC$CNz^p1d}e#DKw^bxyKI5xa2~Bihnw@-Fpkap^u~ubYuj;Ox4JHj zf~LAyH45TY{QFau8}E@`< zMiyu1%dPG5#RPM<|2Mk&!Z+aV>rgp-$%ppY)AamD%qivICV`a+BCL&nov*S~1SU?) zE;&3|J8_JA6rbd0-#zl)U=C>wst_Ol5;`-H73cB4s5EBP3Yxx}JslCkjkz{mo8Mc4 zb})rZYio>wj@`oyhHJ#TPd+wH>*(s_NzO4%GU3GpD6Nc2`8W0$dHOZ5X`K`o6zYQC zwoA{zBxH7jocy#oP-9Ce^r5y5NcCnP{rzmg2Ot>L_0*rlFQqaYy^=(vAjI^Kkb7sv z*ry_6=t*$mW*dBl8KY8*(8>Bkk;K{P3HHF1%kd%g#fl760xy5h{r6J)dra5g_hSPm z5l<4-HtWe`k5XGtF^|_6$(ukuo4vn7Bqb4ue=IMeh{Yyk7~wb9TR}5XtWMj^n!FyE6y&uJSVwEXy6TtvYkKRhF67A z-pHoURY#`lAr2by?n#&L{Ff&zt+ohgd~saX@L*rMjp7rHs(68OFGe3J2q#(a-MD~# z$29-K9|$63`@jltkex;%^jr{&mtu+KL15fD_d@!ZK!c| zuxS4lEwST5JrT=MYHSm*_Pp>(d|S=s=Qq|F)@|92n@{ij{Yyt)IEHSLvV@1vo|RYkIr+Z!l7&S>J!+uW|E)7WplhYC^~LT_?W|De z{*VYt8VRrg?rJ(0j4F`6>p^k}x8vnQ86r#{JdmihB_812XC&B=Kxfo396)$CYZfwX z1WS_=_paU0s9E1NZ-5R=zCoBbObd12b-2Vnw@-h7#X6r;oMKgHR7NssK*i!9B7HFC z#c$HkZprp{p)?xd;c1XCfC6|7iX_QR`6b4eH~13RTnqW|9{to?Yka?GDC$5MaMKPU z(q*f90^lQtz1g`{kO4a>obqWGW=>=zf+`-7*n9W}^z8*WXF}~EmO3dr7-#@G0U*s= z0iRWUkAQYZSaA&;e0he3Mop7}f)nnf1i%g>IBrwj=cB|xA!DXVh8BJYJZZ>A?KY)8 zyf?$QFWy?(R(uj$3N7Q;Q-uVigkG?;Y&JW2It#dhJo=7XV%9h zk}X`o;D|GYei-=TO@s7%Z)WY2OU_*V=oDPZz_q}|22 z2eR}}Pn|EJi<-|un=pgdJIES4kip+9vamE;=xBx(=9yMw;1YzHuK*eFIp)HTEANsv`Y{7K9KW)|qFJS(l zJ02|x!p9G!5fWP9+J=?erWnrHHo<-OeJZgs)jb4(=LzG&OR~)BUCYa_LZ-98{$_4- zE2K$$Eb+m%d<%#Od+ob5h13x_PQe))0Ni9JC)Zo%gCxjKO%(rpF%rXU`J>805Qe~L z6zT-aFBccNyxqPkwWz-f{_4k^Z=-(-TdKy^NJ6JYQ3DQ1L)8u5)UkooY;1mnhMUc= zec`^912ymiwOHXJwOP7+^sZAHrm+2PgI)z!a9DW!$Mx6U6W#GXY^8*qIrud=0f6&Kgt~GVQQmN9SOG& zfcEgBsH3_F{4hR=NNTqXvAD-j;(p^Uj8__(OQCNgqS5_Rd!K=-m2BonQ z>DRpXPxTqw8*=0Jd@BI0x^>)6ouQZECB;L2;;V!-Lj}@H!s9G(~`-& zdgt_nvdZxBN)a;TEi+of=F z=0o9=EjZV3X&Dl5PJPZg`9yT zSaq3;v9xOl6J2Q?vZFuU)#oR=1!;Qn(}*#1w9RK6k$uvRqEo)*&#pl<;gdvIiWa^$ z3!fUZ(q;Go1?T?Bgk?65jU=m6*myCwac^hmXKZ`&H_3N1zc_KTcpas3vI%8TkYQaC z50%yy`S@EXX|uQ+qhzv0Ax!7>u{ihHmWIN4^$mrseaQoIGn>&ihp)WrA1u*^a0h3i zmGyDp*ELogj{GLk)=za=*57(o@>f{9Ys#@q1B?-=x&u|#%$_OJR(QVX`LxNk!SA+z zm6mEV%_~3oV8#?r2df5QZ~|&hgxVHKa>G68_d-^vsYo5p@ICy-(3_T{K4N0c`>j1G_Y6} zn2wF7GLPM2nv~`shlE><+12@S^WE7SBLMD}JgM!sG5X!uU-dw8IWCQBBEz#7NG6e4VR%IA1*So*&3?QahUkwed)|lQy8$6Jk;ctG&Z^z>Qp)@!F z5=M0g>C+rF{H6cW;Ev6uMwF{dN*<;9hAkytn*f%rKzlz-=Pt5fOl!sfNej?72@=E? z5p)y;G6sCIN@+iJBlo!#w83ATrpVAspMU*=NdG34Dx)ZAyws(MdSK{G?*VPn=RO^B zuLd#{Xl{8!!WzUPfsGl(2EOEnF$w^iDfZg^1=?zxnkOjh(uxe=;bri1abZEorp+VV zo@(IIQW+d*2tR#{GA7CH@m|BkzHDT=sl8kBp#Yd*tgluT1KsY!lN0$Qy((RayUf*iF_V zhd!sTk^(Z^o8afl3soWlS+Q$Gp-`j-N)&cW<>|rZc6d$8maP|zD#RLS zye*yU%vYkqnS}9)xz&Zug7GH$68m!L0yEgtc?i^_PHnorLis<(;gDV>f`p7P_?wcwN?1HWWTw)D&%Qc!~yV zhI&*%Z6DA9%jTftAw0vM0?>Ev-!5|(Cx1e3VNbdsF|v#U;fUW_iAeMK=A`*N1Sjw; zoKG+_C&8{mo-sywEhLy`NzyYf&eY@6dea|7o=_ef1?}>TA8*ACF3H?p$Py;?M{Z~t zJZL`6zF8ozJW4t$ZyXFjpGh1a(muNEho)j=k2*1+pr)cDWc+Q4>v569mMl)*-^lkh zSP#C1Gw5G#X#X&wxnapX0}cQ(?C;<+s1$}lCez?C^wugD9nEUk=g8{4{Vi{;=Ggd= zkuTccWO-I#5k z?#(Pq^EP3u*L>TrXZ@!nkv{%=HDrS!JgK|Bg+dn|4?kOMOp>%TkK3>8@QosC_IqHO ztPml|>r{URy-kKj6rpk-pHKwK<1(DqK}mvzfhLD)aXUm8Ze-xk;`U{LvFt+_>a<-A z;p3v@3c!AsOV^^pUr)`*{w!$fIZ8pN2KsPmi?46X*?n|Hd52<9sbRPlNRBrf{fydr z`%B1TVXM-NiD5)ShY;q~)l$3UVU^Bvabbj5V3`=*%0X_`Yih~V6?Xr|`N$PDgG;%# z`%4Dv+1to3K^Xmjii3qp$dc`o2p3 zZxC?{^V-MRN>(rR!EbL4JOdVQ{4P$7ZyN5T7o%PnIXXbqT?Qtqs=2DH$Z2vDyB7O3 z^L8%WTMG!m9Bmi5Gq!|jB}1prW~HBq-P7kgW<8G4?GxR(ZH;<<{0pLJhw`?p#dfv+ zMERx9fRV!nCT5pC`b^)XA4$RC%TN5fRfzl&3_Y4yTxv*s4fqv#Uc8Wniw6*>BqZuk z&G1wJwJa=|7Fkil)~3kNPZD#1BKbeV{IpP3)FTR2_Q|h*w5m#F7g(a>*2#Dw2_jeBl6_ zu?N$)o^MwdVwkbwTXi!s-wP!LNmymtL-#np-3Nx zWH`gouC`?wznCXce}co#g`mxGUd?~Y38y#<(M$#IWn&kein994J0YI#C35$q`I-=7#Q z0J+7G-{i%GOZ|PH>>m-0D#`ii8Qd`%ASUY%OjfVUfA^Q9UANk*l8#K89YdmkcIgvS8)LoiwTI8>j@09wC-(s;*wpy`$VUKwBL!OobQ zDn3V)n?=^K8e_#0T$HLqR))CeZs#Fh-t`!5AMHwj5RDi@N)wd?t%v5h+2K8-uh<;yl1y9a76d^=@3jBuLtT;l>I{cg{S#GkY3F+#!5B% zCTgt%5VA%zGQQvFBMhiU7C^hP_wde0IM}Pw?1;Cd09_`aM^c4@iG9JLjQQ6|&}N9y z%=e(_m8g76&=pxmHsMf!=b0tn=2aY2>K&Iq8ZC>`DN0gPu0?Q|{}`op%M)oGlxxqV zfyp(LLvx@=5g5D*WmIbw%9n)gTs=b>=!&d`G$( zmfvY97QY3fiKy0$$d1$sTSbR=X13IXV>q9(Oag*8s#^09cFe zR6iTclbXNL*ssBPVl505Pa5|JHp?v`%_w|s5vs}4n|zZ3TN$_cV6dZ01AmoUM}Wz<`a)ccu7`74|KBd$wTP@H_~yokytPNsDcaUj=%Xox z&s~@Djm^1UD!Q~Pr|^fgwM=l%Xc%_wLk{BYt;d%o)Xw#)BZy1BcK+v{%XzcAy7 z{EuiTodCR!h8b(p1iwBy6{xljrZ59XVxO~i52Jr^L|Yi&AAr>KjoRA&0|1uWK~Y{g z(A2@gb3V|F32M@!u=n@a#;ungDQM5WL#`zpAoZs>gQ~Bli#LL3veR=bRc%iRY4!Cr zZ#u~8yHf7dEH|f&Wzf%a6DE!jKG#j1;4^1jQ(?vgo{{70QFC_cG)s%J) zFYaIb^QE>DJe1sW+F2xPTM+3E=4wY<&5q@HBiz_l&#)kw#(?W-v$+wRyV1`z`n&ol z?yE@dk+b;J`RKs;ZrOqO*u}{svv@-4^_1};(p6oPqBp5(J$MlS7_;_f74O_8#azW1 z3vuBK@NZ|Y^q#rt=bQ=lzmBN1CH%)Egr;^$ukMdKEP-Z<9wn%ZsR)&(#Yea@e)wRR zh|1~?Dh`^@%1$K&V}Au9ytxVR)Z{IKEegrETK6heNd7G;k5-RBhKEd*z_T zDJj*Lcz0y_3=TEEi0Vz2x6W$x1@g5F!?rQ5D3`^<>k)&!cZ9`SnzVu$FSQJx*E0Tk zA+sbIB_tA-Uhi|Qj;&ulebo)q6CwkhyybGk6(aVfv*M6KoU>c1%CQ)6M-4Ka?_3lz zpBD`}miqo2J`?56W`4THQuxcK(ktxhHw!c-fNPH*C1J!EHGzG4ZwYR6SKZ5=vj$PT zOrNIsk3t8G2TUB@5o75)lcK5U5~3lk)^be4cd3=>QpPRmp+6vT{wuybIgR`jf^?oX6GRVqZAFQXN9Vzzrbn744;*2Bg z9 z9*B>YkIDDZ$0J|mEhFIh-i1v8!}<&pmidy!f_UsontBty-%pZ*PgL`L@k#GyMQ~!@ zH{m-2Q#Roud_vB{0w?vh({J5Q{ju6%pJKg%e9Y?z?c)a?4vd(sZX4roe{!1MPb&|; z81hE%N14wb$x-p;b-pD=Novg4$pj4HXszhg--L*=w#Q!ZJ{K9E@&i(GtukO$MLrt! zE#+6-6kn#7#M<)y%P?!<{3^C}7eeH?h+F2ODOvY-Oq}b)L>f;I>W1R;N|? zCi%S~0V`xL3sZH$5`lUU155(E=%^|DkvxeBex)_MpeVXMUnC*E*L>{|kI7q)vaF6h zy;_EaPKuuPeyD6lv3AF!qP>&3$(Ppzc=z9&mO0;f2)n=&vV<)Hc+jvGN1WMJb}ye{ zyYodYr+*2E$ZeYb2uqN!^DWB1JusRsp?4K&Q`zfWi@(VgPlB+-M;lG9Q`4bj0^4Vq zM4wM=W)}!?#vJh<`x%n1tSYm_KDQR&UWi)q=KF;I%oA_BR&MBM57WbPpsqxmG$MN}#IXTj*NyV$| zqQ}VS=U&52M2r~vQfiLqV?-p;6yGeCdL)N!t;o^m3Q9RTPEm_t`vR-=p9L&A2%z*0 zniWQQuj>{k5zc#$2>R^Zz}@8QbV3xW_@26~|KQsnMU)L3tX-IQhNf-ogmrR2D>(f*1CPJb#d*Y|9xH;-nm7Qc9vulfO&X?j;U zQv?4jO`1vpf5*TLqmTI=dCF<-r#kk#{{5l*&aUx zwT-hMZhH`-#e}FRyR&@okE&{IqP-O8FyU&^=|NEb?9$hMxU^*X9snV=8U5BCz_RpJ zB-8YV7H^sG8B5WVTp%mnZ7aKj9Sh4w=-=x#W9wfG9{CS3B-?6#{zGYk$H-0Le^2*A zr#87`R?yk5@BddsGH*_+{8*>(_gQ;|1rYg{Y-@GUDrWN=0T#=zm@+-)`)mmom+L2# zxY&c{CDn%JrE=fD!Wi2m_{49g>bzE7F!1_1IC%8dVXX9cSgLWVq$na;95X6D+I_ro zZUy5XO`FPjr_6ggAC~gh3R}qJZM+6{AI!0Q#eZgCW9(W23vV*f9XbYNIA_%j#4Co_*=*#tjwn$e=gDMc}((rn*} zVnxmWAxHas;hNJcH(i{SY?dfNd6G#pTq!Ha_^1Yb~ucExL71rEb zA9vny4zwJI+LB*5!#aG$@4gMp-l0FVKeIgQncqFuCjw_M^|G(Zv>M5?NSi8)JU0 zNgXc-O^Ny&K@SskhHB1AdWBEQbO)MAs{M6IA-yNTFVTXCa%RO(9Ouiec&#Zs*K(@X zPWw^5?oeWmEn$6A=e@*GSCVbdoEkfyg|}&TX_U3|^^<*clJMPNq&L36y8{}uR4!qu zBF#RdU&UB4`%60}Iq$FuLz&nAPf1rD5Y_X<-vxI^A0RDoASiLPf|5r!(xTK6(%q?d zv;u-ON-9z!A<`lTD4_@vqLL@5bSMo1zvuVIfAE&s-P!kMXJ$X2*(ay}VX4(49ct2) zT1}sNBtfA?Utiqh-*Whh-;p7(>kRpGg!-wrQvLwMgx1%%6f=Hbw!9K-w0LM-aP}-F zUy1GNvvq%vJ~0yeWi@&|U$xQBx-f8&S=BZb5`9+IYoBogg-U7*zxa^fJ%8*!vd(t4 z-`t2+DgWD28TMZhAOzaC55bH+$Y%|@*WpSJL<(`BG+`G^HtcB`#lBeV?sKBbfX=c* zI=l{c>%(f&Twmb#R_7D=Da-DzN7%&Xq-EjcU&}Fqf%HVH!0xLIFXNl({5BDpy_;*4 zgQgWl@`Qr|Sz!>e?dxeX*#BbV<^S zqzutZXcLOXsBO0#&SvaSK)|$Dss6>Tq;-&H0MdxA+=7w5@n>|Y>z_TUsvW$#6ny_E z%#VIDm*N8rdsD!zUOCoMC5MwWnHtXM`tMhgn8K*^-cI-csJSrf*JCltr?KrdMi|r( z<(R56PVw4_zvcLv7Qg(|_YKPu9NK#EW^b9J&VhR`Q1K z!yV6*{?{yMPN?z6PS1?bGa#CL6r}y6m#5EDix-1US^p*O`;XR?HoD~Qjc$CZZQ)uk)ovYtHr(=RG%7fD% z>%KR9)g#x*thkWsnl=D_5|1dn6k{BBS3hqXF6ST#^qe~bm-v#lHzP2i3Zbb94}VO# z<*L`kyt)1BLUHybvc;1Ed6~_@)l=>`jpJW`{tnzrCEQv}PpB`5tk`=rbFxY#WBs*z zR8tA$VEjyGud36~q-HIV%wS>>@wG3Idv~OCCi69s1S4%-6pwUcEHo96)ZV25qMPoX z-`yYQekIAt^7mX*fM>6qvSt*=cAHZuf4$g80H4fR%k`{m=<8W91apOz4m9tb!!d{5 zE(o|ke_2WPCH!R}LW;oDHr8hD;#1uR`S;u^f@C}C7w*%i4&M*60>k&`>ze8pKG{dK zLc0`6tfm|{>9$P{1fxKt!C7Rpgh~inDQir~1$eF4` z;B5V4NlioC7DlDFCsXtO53F}{a!Hp3R|C0ED1KWIuZi{>q^GW2^nG~!m6l>$DKin!IR$VYZusQ}5$Ir?Bd?%(huet~!!;esa zik)HdQPDlRmnxhAMnwhNgybMGHO1!L?`%M1N;tEbWpAtB=Uwm8q|@H`vzEwM2+n3D zgJrjuCT^BOK^9khmjBL*={8Ut2LdKeG<;d?uAk8H%E&b{rx@now$2H?85%Fk5`6^1 ztil-d=s7c{#0fve!g9dDv_lBDXSVl%tq1Kz*4l&ZY_B;@o-@8q;bzm8ELz>VIWs+k z{8ajecf1_l%4v0Q8AkZcHs}8hAWO-?3B{*q)T#cwsyvrf+=Rw>`zm-K+opiY*Ms4T z+5UusyO2qsHwgL(Vg>OXf`7u_jax}xi!yy0pgY3_Azo@O5~$+m2O%Zd%qZKg(XQSf zd)p4Jx~l%iF98*KpzeJ3Wk zlz}&lZap4nltcA4O7A$muE+p+s;kSv9&&0;QsI}6-L5P6a6ry~lm5l@L;SCG4#{gL z&Dv{5S29E?!0jv20;{$f%9um8T;CNS+lH)*wp``r0J@&%7I{@Gx(CghjQP>9C*g& z3p#L_Je~Bz4QK#0=|ctY3Jbt*$KTyo5{(f4DTqKR^V+9y@|<54LBkj0JY9o+>{za( zuS<&eu)8e^LBKzPNWG9gitRr;v)*6Y!(0$(eP8j522uX#f`?O}ue53Z=7-yly>>?) z|8}n(Ce#C08P~dTl0CN9itSSt0*HQN%RS?ABkaiPRXuta|HcbMF_rk09wd?ImsQr( zGET7?UOORn5X_Pm3U24M@b_B%>tov)xtWxEa)opuZ;-L=F>_RqX!74Q+812@N1aBD z;3m7@l%JzxG9=D*o)wF<$VC+NPzrvI?(Jrs)LE8AzfS$xfAcCBD@rPFc=xaW3uTIZK0LpR-qFLo$dMKTcA#kHW0lQRS6~w=nJ{W zkbk52t}4L~#J0>Lze{-TGP&HsilD1;rQyD^`%&0(y=Jc+D%3^CYpNV&L8MVXYfUKN zgRgYeqXfDFsPagKn;Lg3hmW@z*}X2XeKWLNw92KbFVZAG6Jh}1CsaiIs#wiF)5GSz zu%~P81~uObV!t#Cg_%5#>VK<6sFc6n#ge~?-)l+xml$mJKNF_~Ny`a4xrL6AVA2D7 znp%=OLOwiyvE3Hdb%EAhu8M+ z#sts5Rvy#Q@ffu)cx+U3=H9NP)NTUBed^Q)BR6SQ=QLW#_v@r8gQ2r~^2$t@G$u*f zMg@pZn@>Pt=C%UbTKx|DtpMIKUcaonoUo>%?<~*o-rABUw(LYw#&ay!On&N~XZF@} z!GGJKMQ`=rJF4MareCr+faudro|$d&@NvWZ{l$E6nPQg1dgP=l^WbrML{^F{vgP@?F)W<)hWBJP>&bj>7H7PJqM6XC>abJSV693oh|e?#q&M zJyO6AnXo-7)JpZ7%E|N5!Vh+xL=rv08K|RbWWQ+Ay*p5aOhJhxxsgpzpGAwIBYEnQqnF+CBVdeP|>+IA}kfLwI|ue&4H<@2W3_B%nf z#|l1a#Kzsie0`a)9y_q2fVsS&lbiGwrN|769T$we&s$sj!6p918!dbMR?YF9Nq>mT zMR@eML=g7j=@dDVE>%Nl{{hXSx})bzY#lw2qa(?Y6vd9cM3na$yI z96w$z7Y}V}Zc5&GuaBSv;QM1YFp0gEVg#HYuI|}tU*Mn+FCtb$5}g|xhLXwW%mrDP zh|%RAN(PSp$9zOQBTM+KKE*3U+2kML;xqg3kNUkIU!KGMR5{S!TTM*F4K%+oLuPKV@-2R2Up?w#rs{`BE7n*GFZ(W_U*6q8Sguw zYjop`_d1D59h*1~@@RoyiIZ%vaK6Z`)=a|}y3tQk{*i+J(iLaXl4Zvyfd}>k@H%O5 zH{bC-Rr6td&y^=-+h(C?FV=gOyb>9`=3b`K2=m>){P?(Lez2xUyzY8H#v3(PII2fm zD(UEyKBVvH-yTsCyda77aMd>4WMwjy^r?#RBakrg==M>>xnFub;iH#Dzv5Xv`+)NPDQ9qX!RQfb$rjdQ*24ybz69gj zV}|8jglQM5zGpG;X6od%Ywn9}p=*Jbb7)4fTXq{IYN}z3K(6Xhi`$3t4*j^d6b;4> z19urHbh2LH^Hfv$AaI`45#RK_QHco7Zh?EKA zZR9Y6OYi!N)Z_zB2zqEFm~nyZr~}12GMsQI5f#2Bw+bQGsw*_Z zI`EloeQBkd`%RC>_cc{3wyC%-{(Xw1xt*)KEl)D#$8_8ZG}Jac!`L_{2wcL1(&?dO zUa4HTjj2tAkS{-ikz6W11|Bj-4PCd3SB=7bVcNm7#xlevh*j2(#@3d6lv~(g-JE}| z$&s&|KLMm&lf6?kHwXRdbYSuRB=kwHneafDiT2frIl5WLON38S6jv2XtKKe2hLCW7 z(-DiF4_a@CID0G!&c-C;w)lkpzWBQ0ctSn{x$xkWZPH2fcT=NoR|xBMS&Z)^h8?IB zjW}C=Gnytgm8yFhFSd=#^RA7Or@vdeZ+F1~YJ1#);ro*VY!U4}dxT>bP7)DI&Dn8- zF}^pOfIGXE;T(1QYH>WNHT2zPZk+#D>k2~g?x~iI&|L|D!kyxr{w8R zzgkTh{5&CZ`}YrPjD4yjZN;12zLw3GkLS zY3sCG^19EtqKo!zsS1B{fORG0)7LB&Fyp0NUCBdJh`F7h@d#cpI%$@at-cI={h*kr z$rQwZ+fwQU#yydBkZjJrFWU;nLtA+rMw=bmJ=~1}VNWH;Zbxl9$ltFUnuC4#6pr*& zf_Wgf{Ak9NTz!>0oq@0`Sta=3EGCI^sK9_|Q((;YVzJDW8+gujK6POEI*f(-!7w!W zt>C?KM|Oq@-#!x}S#cl7k}M~6?(3DGjv^eWH##1`SM(Ie;c8KUtQ`cm9cndX0pjJI`Y3#{!?-=#8#yD|=N*Ua2D_(Ej}Vw81h3TK{b@ zHc6&+`K-r3@W7*Yg#YUcVd=uD=BF+v$J~uf<(MZ%rDp z7JFKWl%Q8952Tlq^RlU}Fon*UYV6lpA6tSLfM?a4+wl6 zAYJ6AQRW7MOOYzqV>((ECsqoQ12&y(+P3(*Ex7EXWHWf9#F`>buA8~&&3JvI%I0ch z5Sf$D-M7_?F0DFuM92E>G7B#zUk5g2K!y4HP$sxH45nhV`I29y5ln*K%k>Ftu*O}e zkcDnqKyYQmI=zI=J&OH8%~#TSj?ZU4%|-EjyNA2OHogcWAQ&&?E;boXL0%`V11#9K zBJ<^?f}aDksBtSfB9R$z z;(@m#hIb{g^dCAzXY<6x<&3@x(w>{fcZ#?DLb4wp>&QAI=IJnHGPEBaTLLZ{vC8Jl ztMaxq+aLBvW@p<)u8cvN)V>zn>O5`Z>c%5LW9iC*l8Fu%FLpTf%x_Gv6Bp4rhZzb{@GT6{jMTFI+wll&zq$*7kg-#Bo4%xw4ix3-&i7#`AU{BZZ&-HTh=f+w@x z4l_T=t1?`RK#BwWmvjPn;Wf&DDqex1mG_;8jk3zjb?Jm_8Hk^OHAE-gZhzp?g*;?ma! zjLlc5S-u7#bf8`IuIUO)4ZPJqPxs`bqx@I&K$`ugeIXxEv9fajXE;nxoWA$7;ARmV zurU2RS8ijfGt8f}Ut7gw22z4f6tZ7Bd`e36JvkwIo06tA~~a~t+wh^T!|MT zfN0eU3c{T0ZJ3}*I0XK2jRIy7?H4IhMo0BCj0Ug>lqXOD!fsY(yI0H=;ZIGt;#$)- z5XsCBr5$j-^09Nkb3CDr(btCsx5R>)q#(5G0AxR5K=5(wrm{HZK(IVqmse=vYUW}E zP@JC6Pl1ld2fr?asg~nD2?5o5P@o93UV)?3we=8sxWmiF#A!XL2Wsr8VNIf&0J-N) z$jfvU5eNpG`mvcC-3y|7734bEG1X&+kJk<1>rj#+KhKaOsGH!*U^p=pAf4x~fzGG) zx69O$lNVrnwjx5E6)So}6|bQ(XG5y%bR{;pmKtWvD`>PKge+|aNTijr;v~qPAm{ll zgmeO?t>xt2O*IMw6{TP?4RL26_F=AMn-JzQc$7!uz03lTn}^&0qcBL8o%0G85k~N; zua98PW)sVNUt_N0#t*|(>r&$qi6ka2@fR$Vf1N`=c@=bCgami_kz+>pFs)4 z3!^b|dYu>0{|X@RXZNiPTehtkarX*Z-KYii^il^viP#UU#ixHogDn2IC);Ycugpny zEn4cQ4}MBLYQ9(mVgcxvb<|bNAn-fLy5uVEZvfELYjW<4){<%A$}F9wmHAnXnEs1& zh(O0zhRop6bN@;(z?w!o;nKZve^4@IUrauCS~#|)OC?o-gwKdHwyXq)0h*!^`Pf&a zSJXsiNzQIzOY#LZLeXd>vW|8O-4tZY844T-mqCy8cI#blaPI|;t3NnG7xq!!+)a5E}^hT)-)1K>-+(iN<% z>D&3B%GNvz8>5P7Ou?zg-|H_Vv3XJ}D#-m5!|R#b+%T`L>Y)UbgsRP{DvBu|e`l zfzbx==1JA+^Oeq{*)Cn-o|XH-sRr9x0DHj)xR2<*KUADsj@V6-V=4~AOrDHyPA6rx5d=;-f~ZVQ(2MWDr?J2 z(4>pTbZcVx0`B!gEZ-+=OF#>Zyx}s&pBb0|GpPn}ZJ*<-T>=~lU?~R>gMKrig{jEs z^GAt7vd8qjMf_>y@%{eu@1|7+6tf{6V3CqKac9`UHBDN!_v@rZvmj~nj#j&qs?v0@ zu+3oHHFeLmJ0@7-d{)(w@yGi{<~}z*zmP1e^N@HmIVO3rAVvho7AS=w;?#cy0}?D+ zhpYwu@^yJrkmQY^yTX;F)r_LqhDes4Uwc7jK^{R0$jT~+dB+%}`&RBqC_{3>nCti4(Qk;NRh>1dUzP8VY4Xu;Cp@uE2>U)t z6bbDA7;y%rsrv!Gm~6fo7>U`E?4t&3jgEjC0Xd?z_P;4QDOkEqOb@ua|ISRS3&iOh zoaP|Gf<8zMr{?69PW=^LB+v&8L$!eKL#Fl2LoQ}PoaRx2dRAFxQfUHTA;}bm?_SB= zL2enCN4_#}w8eE(gxZs~1<`EDHD zY5{8S=c&Abxr^6!n+A~w7U59nQKH|+_?D}-Dm7%ZNLQHMbDqUL0zld$@SSQ(7Un$5 zEpHUM;p$GzWHhYPTmt?c-Txl zoW5%XB_?8_=Mx1;_d~#dUvy)n>d5JNlSrkLL{cJ6kBKf1EtUu&DH9ycc28?oKT6x` zt7pH1G6y4^1t77e^O2fanR@C@s5<8CYWHnKxnjz@9P8q$P1(xTAbl^C0f9vP1i6eP zJT=>`4BmX2u8VlOLj{2KLy}1L3^x%|yrH;Ulr=oRLWp1XKS>7qirY~ums}-g@9Po9 z%!4A|@7AWZ1W!PSda3Qo2suB`_h#hOT&kr!nr34i0hp}`01WDFq$vP+P5F*N3@=|# zJ^h^!efkq6UtZtzsyCAj@gf5n>P|{npTkqOc4O=qam124gZ-Pl#t)5j1!ZXhPCdKZ z4A*X-$DsBb*fKTe%GfM0GZ`SIUj%$Bs%CQ{B2Kgg`1$l4g$ZnE&@Z_WK10$CS}eY32`+Z0{3tZ;XNqSdX-MQ3`I< zVo}51xhcDjxwK^ALF%Qh!e%>le`AK5i~&r4Au{&*U4cV=l`D6TXG?VDvTwdDJ~^_` z5xAZ95<*J8lLbM&PVAoty$E`&)aOmKp~>gP`>Qtv3KI3Myp+z)Sh;LoVC0(v+5jVl zhu?HO0VO&xzOR4$nA5e{L>RLL^1B=n11EK;&+nUGr-LuLugL@#4*Lua73X`2E))Ah zAU`z#FOw`!TC)oA(#yajAY zVF;w8#K9N=EqS&N26h7c&%p*%IYcVJ7I6+8N(p?&B)@p?(y!3Q3{m?}tgX~12 z?Dhe>7c2JGx5Xbrq8IG`d-muugm3}DXR|^;K*b@L^U=3Eb_l+n;@bh>cm$+#t^x-# z+0?E#_qPcYfOrh_pGK@nHT;Ki#j!QFz(IqrR@c9-nbDzc>D@s_uV3kc3Q-0L9>h%} zYM|LshVYnr)pAHm@V_~gh;Od5VW!Q@I>A=y{$Pb4Eqk|dd-O0@37&)j83u?;Q-HJDiTtgnbj#dFu-ft8lM<;0C?O}03iTQ;exgmz*jSvZr^&m) zI#K_x_u5f7@WAXdC)jV%?J{uQU6`v-%h?lah$?6({VRcD3ukxC)_lMD8whxb?8r&v zC0|B}Pz0zEsk&$PWbkEhK%5y3X9T+aNV*$~2?QqM2N4{&5=0?p;BpRlZp#nEIuf&H zhUsCKjQ*3#2CiLJA0ESuzRZ9`S=kfnvX2jq!P{!2%nNMI=KjsL*93xdF@dOX^6^0< z*^|Vqr%wK|ZAp_us^nf&yfFv$ea{T|RA7etM1&K3&(%FRKJ+7>6aLq4cj-MOo&xaF zrhwbr2l;&L50w}0ghSahC{S5uqq1P%=4q}-P`0KY!B?TK@YwA<0>xUnq7@fZ4ce)C zGa#+j440OX*pI@}*)#2rg_52A6FkkowImO|JN_9|D1R0tst@|OwWttgh#WHiOrNxJ z1JsujD7~*@Wj8L!GY#xtkr8YK6a^?N(&r=c%d0Z}--@3SAcx{9_5-pI7hNg|#eMU@ zcl_WKicCRfH6s}52+)GA->EJIJc^Ow8+yTPkFdqJ6+n(OFEF$01GS?LDn}BWK#_*} z1d{FoB=$=kSGPE*bSLL5D&T$=6^e?H;U*I-)(5HzMY&Y1AT{=0r0X6D&`O=nLh`L4 zxU*7dbhL)L62*B#D2j>DK(wn^Y5%WLxBxSdsV9sPya(DROW$N<>=&XPq`Y!P{=dh6 z(y4&=Ld@t)eRZcRWDL2Tge7s3ZjzR(j)EUXfuEN*ICOtK3b+6>!%gM@`CY=6m@nPl zcW_z*gf!>1yP$L}P{qMsMtpxCRP%$vDdv?zRGQ^(Gmtn7@ZTihgEPS^0Pk$u3R@3{f{jzCa>icOlmy&u31Kll3w< zMBw-q)({*!%oQW-rmTKxkx0LEt2C1oV(t>c> z8>nsrl9D>Q@RAsN)WZNT6B{aAyC7WD-Z=pxiw@!70{+r^@`29^!Dn1lIC&wssH1ZN zR2JF{MUK*T-wHXyE>7|nsRF$O=}}9FD`i~qv%xj=y#I(O$ZQZJYv8lmeLl3xu%DNf zcF5qTD1LV?I$OFy<1OoZ(-?`hjiO)Hk9V%?07{r(lqqmalNSvPdfp|6&qrw@nN&jK zuBv@a5AYh5ry}TU@uulesaPVgPdH;4Lhi~gPCA`ZLD(pU^c^X1Kpajt_uC!P6%rL0 zMIz=9jYIBU0$c2z1M+C&aL!K7$Ivf~J_?HI-ss-xll6R$41X%ZV4NzZ!35RqPp-Jk zjkIVx{^bc4mDPpTWrfP7K`~<{C?~@~PjRv^9)49WrH{xPa#v)k`&JE_z<}4`5CNn_ zsEC6}dFzzcv^223(%*2uoDq-KiO(`rgq>(r3^gcPnEdr}A*N6*^vajEM~09zTN702 zB@?vRr6KeKy#>m7v8TU1sXZ{#?dL4DWC0$=O@s;HWP1*}EF?VzYl*(9c2z0mQX<#b zE589~DKJfupQQ;3k5$D)8Kb(?mxy_t69lAOsfaXYyeLP~fLrw?+e2j_1nN>g zqD4{^1V&w`h)%{Y8Qxovm2L%-AM*mkEytap^cSFX3xWNf5V5$+N4N?=+guQCLK%ml z8S9Xl?T0;uV$7eSwSVdd6#r#w;S8OaIU8uIqc8!$bRM*_I*@Elo&Q+Vj!`A_rJ;)U zSsxean%g+#V<;x882qoiZzl8CVv|OfMCO^Pv*@Csm>{q_uTo4hgtdI+3rUk~95R>Z zVPh%;n8;EQ#|^2v1$}imqF|l?cfh`~bd4S)?G~uwCKGfvQwS%-6FDJG#^`U`^j>=V zOoRgGuELu(DcwMwsF)?Ma=_BU6FNO}wzM#34wN#SgSyd3%hR_MggSg9@FYsdBE#9? z6u3v4ylK6X4e!*^Vvhc3?!f&y)~!~(dw_K=xDuDaWlp*6Tn-aiMts*IGvGVg&twvY z^Ee1Y+ceifEyAgYmkaX>G}m$`D7&wddPsHvZ3c^Rjor4*FKl{Ttzg|2HHk + +--8<-- "DESIGN.md" diff --git a/packages/zarr-storage/docs/index.md b/packages/zarr-storage/docs/index.md new file mode 100644 index 0000000000..25db68c637 --- /dev/null +++ b/packages/zarr-storage/docs/index.md @@ -0,0 +1,67 @@ +# zarr-storage + +A Zarr-agnostic key-value storage layer. `zarr-storage` 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. + +!!! warning "Pre-release" + The API is not stable yet, and any release may change it. + +## Install + +`zarr-storage` is developed in the +[zarr-python repository](https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-storage) +and released independently of `zarr` itself: + +``` +pip install zarr-storage +``` + +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 import Found, Missing, Store +from zarr_storage.backends import MemoryBackend + +with Store(MemoryBackend()) as store: + 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")) +``` + +## 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/release-notes.md b/packages/zarr-storage/docs/release-notes.md new file mode 100644 index 0000000000..d0687d8758 --- /dev/null +++ b/packages/zarr-storage/docs/release-notes.md @@ -0,0 +1,9 @@ + + +--8<-- "CHANGELOG.md" diff --git a/packages/zarr-storage/justfile b/packages/zarr-storage/justfile index cafbf32765..02befe47dc 100644 --- a/packages/zarr-storage/justfile +++ b/packages/zarr-storage/justfile @@ -17,7 +17,7 @@ test *args: # pyproject.toml. CI's matrix is written out in its workflow, so a change to # the declared range is made there too. # uv fetches an interpreter it does not have. A difference in how a version -# materialises annotations or resolves a stub shows up here, not only in CI. +# materializes annotations or resolves a stub shows up here, not only in CI. # Run the test suite on the oldest and newest supported interpreters test-versions *args: #!/usr/bin/env bash @@ -52,8 +52,35 @@ typecheck: uv run --python 3.11 --group test --with pyright pyright # Run everything CI runs for this package, on both ends of the version range -check: lint typecheck test-versions +check: lint typecheck test-versions docs-check # Preview the changelog that the next release would generate changelog-draft: uvx towncrier build --draft --version Unreleased + +# Build this package's documentation site, warnings as errors +docs-check: + env DISABLE_MKDOCS_2_WARNING=true uv run --group docs mkdocs build --strict + +# With no argument, uses port 8000 if free, otherwise an ephemeral free port; +# an explicitly requested port is used as-is so a conflict fails loudly. +# Serve this package's documentation site +docs-serve port="": + #!/usr/bin/env bash + set -euo pipefail + port="{{ port }}" + if [ -z "$port" ]; then + port=$(uv run --group docs python -c ' + import socket + s = socket.socket() + try: + s.bind(("127.0.0.1", 8000)) + except OSError: + s.close() + s = socket.socket() + s.bind(("127.0.0.1", 0)) + print(s.getsockname()[1]) + s.close() + ') + fi + exec env DISABLE_MKDOCS_2_WARNING=true uv run --group docs mkdocs serve -a "localhost:$port" diff --git a/packages/zarr-storage/mkdocs-base.yml b/packages/zarr-storage/mkdocs-base.yml new file mode 120000 index 0000000000..5fcab1ffda --- /dev/null +++ b/packages/zarr-storage/mkdocs-base.yml @@ -0,0 +1 @@ +../mkdocs-base.yml \ No newline at end of file diff --git a/packages/zarr-storage/mkdocs.yml b/packages/zarr-storage/mkdocs.yml new file mode 100644 index 0000000000..7a66600306 --- /dev/null +++ b/packages/zarr-storage/mkdocs.yml @@ -0,0 +1,32 @@ +INHERIT: mkdocs-base.yml + +site_name: zarr-storage +# The package lives in the zarr-python monorepo; point the header source +# widget at the package directory rather than the repository root. +repo_name: zarr-python/packages/zarr-storage +repo_url: https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-storage +# Absolute because mkdocs would otherwise append this to repo_url's subpath. +edit_uri: https://github.com/zarr-developers/zarr-python/edit/main/packages/zarr-storage/docs/ +site_description: A Zarr-agnostic key-value storage layer for Zarr implementations. +site_url: !ENV [READTHEDOCS_CANONICAL_URL, 'https://zarr-storage.readthedocs.io/'] + +# --strict promotes warnings to errors, but broken link anchors and pages +# missing from nav are only INFO by default. Warn so strict fails on them. +validation: + links: + anchors: warn + nav: + omitted_files: warn + +nav: + - index.md + - Design: design.md + - API Reference: + - api/index.md + - ' zarr_storage': api/zarr_storage.md + - ' zarr_storage.backends': api/backends.md + - ' zarr_storage.testing': api/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. + - 'zarr-python ↪': https://zarr.readthedocs.io/ diff --git a/packages/zarr-storage/pyproject.toml b/packages/zarr-storage/pyproject.toml index 2ef3287654..e01586c114 100644 --- a/packages/zarr-storage/pyproject.toml +++ b/packages/zarr-storage/pyproject.toml @@ -45,6 +45,7 @@ testing = ["pytest>=8", "hypothesis>=6.85"] [project.urls] Homepage = "https://github.com/zarr-developers/zarr-python" +Documentation = "https://zarr-storage.readthedocs.io/" Source = "https://github.com/zarr-developers/zarr-python/tree/main/packages/zarr-storage" Issues = "https://github.com/zarr-developers/zarr-python/issues" Changelog = "https://github.com/zarr-developers/zarr-python/blob/main/packages/zarr-storage/CHANGELOG.md" @@ -55,6 +56,23 @@ test = [ "hypothesis>=6.85", "obstore>=0.12", ] +docs = [ + # Pins match the zarr-python docs environment in the repo-root + # pyproject.toml so every site renders with the same toolchain, and the + # shared packages/mkdocs-base.yml sees one set of plugin versions. + # Bump them together with the root. + "mkdocs-material==9.7.7", + "mkdocs==1.6.1", + "mkdocstrings==1.0.6", + # pymdown-extensions 12.3 changed the Highlight extension API; mkdocstrings 1.0.6 + # cannot drive it (Highlight.__init__() missing argument "md"). Match the + # version in the repo-root uv.lock until mkdocstrings is bumped everywhere. + "pymdown-extensions==11.0.1", + "mkdocstrings-python==2.0.8", + "griffe-inherited-docstrings==1.1.3", + # mkdocstrings uses ruff to format rendered signatures + "ruff==0.16.8", +] [tool.hatch.version] source = "vcs" @@ -70,9 +88,20 @@ packages = ["src/zarr_storage"] include = [ "/src", "/tests", + "/docs", + "/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 +# of the sdist dangles and pip refuses to unpack it. +exclude = ["/mkdocs-base.yml", "/docs/_static/source-version.js"] + +[tool.hatch.build.targets.sdist.force-include] +"../mkdocs-base.yml" = "mkdocs-base.yml" +"../source-version.js" = "docs/_static/source-version.js" [tool.ruff] extend = "../../pyproject.toml" diff --git a/packages/zarr-storage/src/zarr_storage/__init__.py b/packages/zarr-storage/src/zarr_storage/__init__.py index c5ac6b8a9a..0bb50a3f9b 100644 --- a/packages/zarr-storage/src/zarr_storage/__init__.py +++ b/packages/zarr-storage/src/zarr_storage/__init__.py @@ -7,6 +7,8 @@ operations with the resources of their `Context`, and are the only objects most callers need. """ +from importlib.metadata import version + from zarr_storage._errors import ( BatchError, InvalidByteRangeError, @@ -62,6 +64,8 @@ Written, ) +__version__ = version("zarr-storage") + __all__ = [ "AsyncStore", "Backend", @@ -114,4 +118,5 @@ "WritableMany", "WritableManyAsync", "Written", + "__version__", ] diff --git a/packages/zarr-storage/uv.lock b/packages/zarr-storage/uv.lock index 4c68fc2367..7564d8df50 100644 --- a/packages/zarr-storage/uv.lock +++ b/packages/zarr-storage/uv.lock @@ -2,6 +2,194 @@ version = 1 revision = 5 requires-python = ">=3.11" +[[package]] +name = "babel" +version = "2.19.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/32/44/744169ce3677a541439bc9506ef08bd85674e9d6e3895ebe5a87ff65fb7a/babel-2.19.0.tar.gz", hash = "sha256:fddd2cbbbac7c299af3c2880be23609c331bd94f0912baca6cb0abfe054dfc27", size = 10695455, upload-time = "2026-11-24T20:14:32.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/3b/ddf4b07be846bfa361683729b5948c9c61a87fbdf09e69540d8e586bb7c5/babel-2.19.0-py3-none-any.whl", hash = "sha256:6d49734aed1d595b2c065d012174df8c83964692f26fc461702281634dd7555b", size = 10983582, upload-time = "2026-11-24T20:14:30.163Z" }, +] + +[[package]] +name = "backrefs" +version = "8.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/83/8b/7e4adda5f54c16aae9363ace26265cf702f77885d10244e597c4896c12c8/backrefs-8.3.1.tar.gz", hash = "sha256:7b76f39c09d29740a6323be8d613cd9abee3068321c98ba8eb871ed23428eb20", size = 5947622, upload-time = "2026-11-20T13:20:19.038Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/16/23/46b3abba813aa7fe5a8c57ba9eccb956d5f5a453cc7a5ef1463684b5b68a/backrefs-8.3.1-py310-none-any.whl", hash = "sha256:f3013ec3cc3ceb1069fa31c0432c73c2d72d652c03d082b96089745c290e7a10", size = 386417, upload-time = "2026-11-20T13:20:09.649Z" }, + { url = "https://files.pythonhosted.org/packages/4e/20/3583edc736a9946f5034b30f0d6838f403aa877ea4614e0048d8cb541f60/backrefs-8.3.1-py311-none-any.whl", hash = "sha256:c27c66419b126ecf4d54966ad92f0e3c2a8aff0eac1687f57fe2a1b04fa4d244", size = 398413, upload-time = "2026-11-20T13:20:11.356Z" }, + { url = "https://files.pythonhosted.org/packages/ab/78/95ca8ff9f8278f846a2d120f1e56a9083967381de584239ab8c7137d2601/backrefs-8.3.1-py312-none-any.whl", hash = "sha256:4f49546f237131515ed25943d1af4c79956425733bb199cb879da56d79ebb77a", size = 404208, upload-time = "2026-11-20T13:20:12.818Z" }, + { url = "https://files.pythonhosted.org/packages/f7/33/4add6a4f4f48254c9cc7bd8a386ef35ed8ab4a2a9e00c761954f2733a0e2/backrefs-8.3.1-py313-none-any.whl", hash = "sha256:5e3fec5e2d2405da135c8b480df12005e2245500c12a60ffd3f496e4acb7cd79", size = 406094, upload-time = "2026-11-20T13:20:14.4Z" }, + { url = "https://files.pythonhosted.org/packages/ca/e0/cb4aa24357e79229441ea37467a8ac40f65110b9b178ecf924594999326a/backrefs-8.3.1-py314-none-any.whl", hash = "sha256:d818aea8a704e41c0ce60c619e23e136fd5fe87f0fdf0b601107473c35d2d407", size = 418265, upload-time = "2026-11-20T13:20:15.864Z" }, + { url = "https://files.pythonhosted.org/packages/66/18/b6566004d8d1f6bcc5079790b8f55b54468ef3a3d875ba8780e60387c182/backrefs-8.3.1-py315-none-any.whl", hash = "sha256:cecce5f4290b0eae0cb30a6e216c539465393218e6596ed164d82d20f2d96a54", size = 423695, upload-time = "2026-11-20T13:20:17.261Z" }, +] + +[[package]] +name = "certifi" +version = "2026.11.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/51/33/4cd27639502f010084bcef7a2036391dd637439901341ce1a530f36f6e51/certifi-2026.11.20.tar.gz", hash = "sha256:af1cb240a8133f105aa52684a3a3258339d7f2fd0bd4e2812698ff5cf5588c4e", size = 128901, upload-time = "2026-11-20T23:37:49.522Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/39/5eec3296860b94ac20bb8ed807725b88f6adfab3f343df592afd975f5f86/certifi-2026.11.20-py3-none-any.whl", hash = "sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f", size = 127913, upload-time = "2026-11-20T23:37:48.117Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.5.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c2/c3/cae6d3bdefd96a941ffc247c714ac4babc488a69012e11c058f6c17c6c47/charset_normalizer-3.5.3.tar.gz", hash = "sha256:a250888753faa289e2997962fbb17c4960cbdb58575533ca6fceee68c224bdff", size = 189359, upload-time = "2026-11-23T02:46:51.755Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/20/f2/fe2bc8a01ed1f3ede348d8afb8e416e81abe801a4ad789a8c5276d95b370/charset_normalizer-3.5.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:01b35bec964b92b89bdf94adf931d2e80a15f1c7b93bf850b4430cca23f7a2a2", size = 409498, upload-time = "2026-11-23T02:43:36.288Z" }, + { url = "https://files.pythonhosted.org/packages/98/ff/6b85c4ee2809f4dbfcee89d128f64d2e5141f2d4c3191cb00048bb93b150/charset_normalizer-3.5.3-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2a6f937e0b70133d1f826d0a253331b6fe1a4c874808cc12e16f2fb8177042f4", size = 263382, upload-time = "2026-11-23T02:43:37.485Z" }, + { url = "https://files.pythonhosted.org/packages/45/16/fcd396b14758f491a8dcb6c81373f0d2e3ba8a28d3cec4c1dea24ec0bea0/charset_normalizer-3.5.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:90b1ff6cb9c7a204a3b79b1b0ed6ac8a1d8fed3b6dc69e50ae5de0f358ee81d4", size = 245172, upload-time = "2026-11-23T02:43:38.714Z" }, + { url = "https://files.pythonhosted.org/packages/b7/49/7fb9fba79adf9b29c19f9d0ff5cc9633a5f59b5f4ed0af2eab6be1fdbbf7/charset_normalizer-3.5.3-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:139aeb8ca63946dc79364c37f2c9cfe5c1b7f3882f2c47484d0e54bf14b921b0", size = 248633, upload-time = "2026-11-23T02:43:40.119Z" }, + { url = "https://files.pythonhosted.org/packages/b9/58/4c7e8cb06d3a158f0d3f5d9c83b9048db30077b078dd7b13b49a412ad0dc/charset_normalizer-3.5.3-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f7a841170fde40b0e1345884bee09ceca7db49a9291fa340089bec66a366c243", size = 291866, upload-time = "2026-11-23T02:43:41.34Z" }, + { url = "https://files.pythonhosted.org/packages/f9/6a/ea6c3a53861c624ade21df448f28091f1f809bb87c56359e27f78eba680a/charset_normalizer-3.5.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:56405211fa124c393eea14b3aeacf5b90de72b1f69b0a60c9bc40b01dfe71a42", size = 289387, upload-time = "2026-11-23T02:43:42.746Z" }, + { url = "https://files.pythonhosted.org/packages/3f/6b/8b76a30025bb27f32eb1d6684fda8ae95789848e02cc94e25d058a72b883/charset_normalizer-3.5.3-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0cf4cb8d75090a8da3bd30c0963b2c6c6114e791c6fc060c3cef8971497b1f04", size = 270972, upload-time = "2026-11-23T02:43:43.969Z" }, + { url = "https://files.pythonhosted.org/packages/3f/6f/95e3df1908c796c8ddb02302b48d49b91d9a1791c32eaf04425239154abd/charset_normalizer-3.5.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0ca2da4a505fae7ef95922f8d48235b2e49ff8f10f4edcc0481e5f6526ba3841", size = 247844, upload-time = "2026-11-23T02:43:45.264Z" }, + { url = "https://files.pythonhosted.org/packages/c5/b7/e72956933c09a72e2ae0c6aa75ec2689aa3f8297625a037772146bc6433e/charset_normalizer-3.5.3-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:09833ba78c91f0d1fd06387c69dae9f079428b77ea05eaaf1553eecead31fb68", size = 251932, upload-time = "2026-11-23T02:43:46.573Z" }, + { url = "https://files.pythonhosted.org/packages/30/b2/78a30d82ac9c712c2cf64ad95983c2ff7ebcf05830ff319d9f77827c4969/charset_normalizer-3.5.3-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:28d954a437bfa5fcdfe7ad8902cf4347a8486f34a86c5f39003bc1288eb67d72", size = 292201, upload-time = "2026-11-23T02:43:47.878Z" }, + { url = "https://files.pythonhosted.org/packages/ff/3f/49bb7c3f23ae35cbc3d419721cbf65505c3f8a69edd3b56dfdc4c67d9363/charset_normalizer-3.5.3-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:00edb7682962c596f774bfa126e6b6f885b7af2319f448d327591c284a482de8", size = 270702, upload-time = "2026-11-23T02:43:49.02Z" }, + { url = "https://files.pythonhosted.org/packages/3d/5e/dbae2c2caf099dfcd5cb4b62800e9c39ce39f6595fae5fc7a34077e66fbd/charset_normalizer-3.5.3-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:a43831574e14423103d69fb1357e76e4f2347041c98e8357ab88ef21812e80d9", size = 290015, upload-time = "2026-11-23T02:43:50.243Z" }, + { url = "https://files.pythonhosted.org/packages/f0/99/2f765df40b47605479c3d38a0ccb093e9e3b56baece1f0fbe2ebe37b8ac8/charset_normalizer-3.5.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96387278c3b17bc1170f80693398d0babac7b41df128ced8e27588a7155d95b2", size = 265450, upload-time = "2026-11-23T02:43:51.459Z" }, + { url = "https://files.pythonhosted.org/packages/fa/f5/000bc674f132ea23e06ea8eee6b9b4fdad020774b242cda32eb2dbe70026/charset_normalizer-3.5.3-cp311-cp311-win32.whl", hash = "sha256:6eea31136fd924ecbb4e7c4f3df4b18230409629a22b3896f38a6754d5857794", size = 190318, upload-time = "2026-11-23T02:43:52.686Z" }, + { url = "https://files.pythonhosted.org/packages/50/92/529dd4a3af41874d0cac3c495ec9622c1457cbe7b8276fa8b767235ab8d2/charset_normalizer-3.5.3-cp311-cp311-win_amd64.whl", hash = "sha256:cd5422fd4f8a7859846c9289e310dd95c0d1890c31819667942753e510f88f69", size = 212879, upload-time = "2026-11-23T02:43:53.855Z" }, + { url = "https://files.pythonhosted.org/packages/78/9d/2a2cb4843dc8b2a84b1a97e0a8423d00d41b4bf065c8bf0f7549c572a226/charset_normalizer-3.5.3-cp311-cp311-win_arm64.whl", hash = "sha256:d3c9d5284d64f4c1015d95b751577b260fd6d14e3f8edf21710f4436e7ac4c49", size = 198117, upload-time = "2026-11-23T02:43:55.058Z" }, + { url = "https://files.pythonhosted.org/packages/c6/3b/df144a2ee54de30605fb046b80c5948dca47499383e5efecfbca3c46c2f7/charset_normalizer-3.5.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:92bf85ecec3ad6374ae50d870bd1deb34de12bc1158b5fd09036d4c435c6f58c", size = 388675, upload-time = "2026-11-23T02:43:56.285Z" }, + { url = "https://files.pythonhosted.org/packages/67/92/6db11254f4009dd980e17473a0ee4a4b54945df4d8346af4bef8999ab85a/charset_normalizer-3.5.3-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:e5e4785d8a0adeadfbdf75f4efc357911842674651cbafd7e97f69b11ec3cbc6", size = 257134, upload-time = "2026-11-23T02:43:57.512Z" }, + { url = "https://files.pythonhosted.org/packages/12/9b/2e28514323a452c444c0c0f27a6aae1d6d74a5b255e2cb6d09dbea3c06c5/charset_normalizer-3.5.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70f65dd0c2ed79ea2d9776096e9c7d25e398c2c03eb31877753598d201d91784", size = 239885, upload-time = "2026-11-23T02:43:58.827Z" }, + { url = "https://files.pythonhosted.org/packages/a7/02/9133fb797235f0e46fd0e13792e1cf2dda23ddc7fc58ff55b4a1556b98d6/charset_normalizer-3.5.3-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6b702d36c565f6c650f4b479488f475b2982132ab8d0840d42b1442462c21056", size = 240385, upload-time = "2026-11-23T02:44:00.268Z" }, + { url = "https://files.pythonhosted.org/packages/d4/0f/190e230562c2d6bdbd86d1f310fd2f0ac6989c0a80ce42b71dd97f27a661/charset_normalizer-3.5.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:dbdd407104ebf2360464ce02c7933c6ffac58bd5b64cdf6ef7dc0e787e782aaf", size = 275901, upload-time = "2026-11-23T02:44:01.527Z" }, + { url = "https://files.pythonhosted.org/packages/39/a4/d0994111d32d5b0b91284aca5c63d0f5c718811a79827c1d55a230d16e37/charset_normalizer-3.5.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:61f3258f700412c68fde407e7c749ed6930e795ea8f5ead9a40afddefbec12c4", size = 273855, upload-time = "2026-11-23T02:44:02.939Z" }, + { url = "https://files.pythonhosted.org/packages/e0/0a/099a0cc4078c2411e4d7f6d9bd71289d69e3095e157c301dc4cf4b2e92bc/charset_normalizer-3.5.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:aa2476abf8669be493689634bdb79f468a6fe57b005a5126db7e9f61d1954fe2", size = 256145, upload-time = "2026-11-23T02:44:04.216Z" }, + { url = "https://files.pythonhosted.org/packages/f3/8b/9db93b3aca912fe1ca5babf4b68376b74940dc23bec67e80f1b4c9ec3886/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1b2704f4651539eab50ba104a975b96c3cd5246011aa0755d2dd71ac12546644", size = 241112, upload-time = "2026-11-23T02:44:05.412Z" }, + { url = "https://files.pythonhosted.org/packages/bc/9b/cb69867d3ad8c6d177b65cbd716c006dbfeebb09890bf48eb77e162799c6/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:2c4e0050b732ee3dca3676a5f5cf7fbd0c131761c194f1bb1d24c055fad071cf", size = 244503, upload-time = "2026-11-23T02:44:06.677Z" }, + { url = "https://files.pythonhosted.org/packages/54/e1/706d79ce618c4731068ae958c43cf2123ed80b41e378f2dd2fed0956e497/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:f06e257ee0cc85a7e4ec44f171ae2595fd901c34212f3c9e7ab8fd8621401e99", size = 276842, upload-time = "2026-11-23T02:44:08.076Z" }, + { url = "https://files.pythonhosted.org/packages/ac/fb/1f42f866d6f9e15817017c1495bbd90a3ca99e5af7057828d5c07cb98f69/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:396fdf2d4367674531a7c8d54ecabbc8e5131e3a1a06270285eb99f3140143df", size = 255982, upload-time = "2026-11-23T02:44:09.328Z" }, + { url = "https://files.pythonhosted.org/packages/3f/b0/a145cebd7a3b787638e64e12a15d2b227f6830a65294d137c70ea4b51482/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:b6ea5bf7e3c39f6e56957d82274ac7cfab469590085883fdbc86e754cde76b11", size = 274691, upload-time = "2026-11-23T02:44:10.546Z" }, + { url = "https://files.pythonhosted.org/packages/fe/a1/172b880e2666371817666fff6b9e43cf0e50e8be91e38158fab8c83c29ba/charset_normalizer-3.5.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:366f5efe95a6149ecbcebf779c2594a6a4ff6fc116402826c72ed0eccd6aabe9", size = 259298, upload-time = "2026-11-23T02:44:11.73Z" }, + { url = "https://files.pythonhosted.org/packages/2a/66/ac0ae9f9bdd82fd619c61763115c6aad5cc537234923bb4fc131749545ca/charset_normalizer-3.5.3-cp312-cp312-win32.whl", hash = "sha256:020cabbb90926b2d8b022a5e057ab349f28844b61f34117323fc08c2971915e3", size = 185505, upload-time = "2026-11-23T02:44:12.862Z" }, + { url = "https://files.pythonhosted.org/packages/82/78/7913aa5816c1606298274f47caf208efdd4245a0da1e309a13e518cc007b/charset_normalizer-3.5.3-cp312-cp312-win_amd64.whl", hash = "sha256:40b2ba91f0851aa864994b3c7022e4d96d09026717e6a72e44410d6fb3a74a13", size = 214472, upload-time = "2026-11-23T02:44:14.041Z" }, + { url = "https://files.pythonhosted.org/packages/67/bd/59a418223401d7e85ac15d4a0ae978d2fe802f8acdef50d6b55724edc75f/charset_normalizer-3.5.3-cp312-cp312-win_arm64.whl", hash = "sha256:948fb3649416a70bcdbb267d79c7048e8aa16e989ab9da09f416e67cdd3d6b8c", size = 201366, upload-time = "2026-11-23T02:44:15.264Z" }, + { url = "https://files.pythonhosted.org/packages/6c/b8/9aa05e4bb709dc3f70fe040ca5af4a0bf13064b5a24238988f585f6a98c1/charset_normalizer-3.5.3-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:7fd816f466883dcaac196ac77271d0292eee4a81f4db1191b95d15328f335937", size = 230514, upload-time = "2026-11-23T02:44:16.444Z" }, + { url = "https://files.pythonhosted.org/packages/fe/cb/b42344c84f48204ba696e75424eca12b33f0f046dbe8290bfd2917dffde3/charset_normalizer-3.5.3-cp313-cp313-android_24_x86_64.whl", hash = "sha256:af217012cfdaf6ea5dc0c538aac29b7bd030eb865056cc60f1d973b982b7917b", size = 244366, upload-time = "2026-11-23T02:44:17.675Z" }, + { url = "https://files.pythonhosted.org/packages/a3/08/fb0a6bdbfee82133f43d5c506b865bc9bbef785eefc355b86374ae87f943/charset_normalizer-3.5.3-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:d12571adb9ceeb9ba0640db46433430062f5f1dec89e39713a2a5a8ce3016c37", size = 222552, upload-time = "2026-11-23T02:44:18.941Z" }, + { url = "https://files.pythonhosted.org/packages/59/16/77d291a7b6bc0784a567ef7b00aa3267efa645ace0abf38a30cf3bea0d63/charset_normalizer-3.5.3-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:183aee7e84789391e547ec1609f8269332b9b123d21e97f7ef79eaa474c47e08", size = 226639, upload-time = "2026-11-23T02:44:20.168Z" }, + { url = "https://files.pythonhosted.org/packages/75/59/47eca4000f8367014c2e1be786aa82bd8702120f24749853e6297eb8217b/charset_normalizer-3.5.3-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:499e4bbeb1e79b14756311a1d12cb88112f244423e152d80981d9bcaff3279fa", size = 386082, upload-time = "2026-11-23T02:44:21.363Z" }, + { url = "https://files.pythonhosted.org/packages/21/59/0a22abdaa8c34c1daa886001c3f238e9b09dbaeaa75febf7f8f203520774/charset_normalizer-3.5.3-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:656b9744bac4493561d28b56d7d646afd7a8471254ef7004d849aa8368020037", size = 256179, upload-time = "2026-11-23T02:44:22.674Z" }, + { url = "https://files.pythonhosted.org/packages/c2/22/f1d08fb14f5a7cc6ea88cde946136bb58c3d83038385268e541f424544fa/charset_normalizer-3.5.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fd0341b9dea133d187d7c5a2cd7e21ae6449a7b68ea8c2454f9cf77def11ec1b", size = 238899, upload-time = "2026-11-23T02:44:23.917Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f1/f910dfdeb3c32ba767f8f9b7290ec3aed1fc44998935255d572551168bed/charset_normalizer-3.5.3-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c9d1f467d121b33b06865c94ed5ed8388a9ef76f5e1acc1c8a854ac653493f5d", size = 237042, upload-time = "2026-11-23T02:44:25.138Z" }, + { url = "https://files.pythonhosted.org/packages/f2/1c/7916607074b99e7d5c5d53e88b76fe1a06328864536d3c7228819b7d9cf4/charset_normalizer-3.5.3-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0810592b80dc5a97f8103443460264b588f31c6baa8a20abae7c683435d8117a", size = 272418, upload-time = "2026-11-23T02:44:26.432Z" }, + { url = "https://files.pythonhosted.org/packages/ce/8f/1d97b6b3287d80b7b961019dcdfb66d917ff3063d46ab0ded635e7615484/charset_normalizer-3.5.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:db2eedef732424346f98d0aba5c6ad688b648bc79847f4cc70dfca830130b1e6", size = 270735, upload-time = "2026-11-23T02:44:27.711Z" }, + { url = "https://files.pythonhosted.org/packages/c6/3c/e51672360b768d7af7a56e00e39f93752489d0dd668034ea14f3d58898e2/charset_normalizer-3.5.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:caefc441edff6070a9f9749ca880a22731a1715d9e74b24304a546eec44bfc16", size = 252692, upload-time = "2026-11-23T02:44:29.013Z" }, + { url = "https://files.pythonhosted.org/packages/a5/1c/569563a1d2cf0a4f7f798a6736acb15f6ea9764382e036e37d8ac7ab9bc2/charset_normalizer-3.5.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3ce4e4587e451ebc7d9899a7a1f539ea30a3c712d7bc8e0d256923c697fd5dcc", size = 240591, upload-time = "2026-11-23T02:44:30.138Z" }, + { url = "https://files.pythonhosted.org/packages/8a/64/7e7181b347948740211351c6d41dd5b78cf3bb81e44ab10f83128a80ed82/charset_normalizer-3.5.3-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:0b3fc6f7dd9db4a7782e65dc98eb80b2a91a854cf54a03dd93649be2f7ca638d", size = 242946, upload-time = "2026-11-23T02:44:31.33Z" }, + { url = "https://files.pythonhosted.org/packages/c7/03/5f2f94a3289330678689c0af2da8c31f3e10a8bd77ac8b1a68c97239dc5e/charset_normalizer-3.5.3-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:bed05639ae1bc23df7996a4fd13ea5064ddf60dc7dabd754f8badf060daec63f", size = 273418, upload-time = "2026-11-23T02:44:32.535Z" }, + { url = "https://files.pythonhosted.org/packages/3c/8b/854724ee0da7d44e33fa42cc9a355a5422ef78ad0fe294d7812d8f1bac06/charset_normalizer-3.5.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:a36bba41dc7fd263417688c4daf95a1091f93e1f6957c0f71ad7798907c5a10c", size = 253644, upload-time = "2026-11-23T02:44:33.728Z" }, + { url = "https://files.pythonhosted.org/packages/45/45/4f98894509fd63f8d366e68faa60c268492b1476ef468d0a5397055b6972/charset_normalizer-3.5.3-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b013417037c931583578639cab2523d5a2efc35a584c192d07f4c909b133f6b0", size = 272406, upload-time = "2026-11-23T02:44:34.917Z" }, + { url = "https://files.pythonhosted.org/packages/08/09/c62783ce9f70a78dcab2b63c6079ee978a0f74f22a732eff9bc585c151ac/charset_normalizer-3.5.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8baddc6349faf49edae4d1322f12b681b9e86acacd01874457c997437ef4ccaa", size = 258180, upload-time = "2026-11-23T02:44:36.164Z" }, + { url = "https://files.pythonhosted.org/packages/60/b3/30ac20e447638738c8714c9e893450ed577a7c76ddf5459f461da2f27a42/charset_normalizer-3.5.3-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:6dde7edd9ba5005389bc7c0ab461411f281dbacb2b06e52bd23592eba42bb503", size = 145567, upload-time = "2026-11-23T02:44:37.27Z" }, + { url = "https://files.pythonhosted.org/packages/aa/de/c352e4d1d7aa85956db646cc6873fb7e81c12cdda3446401c554b50ca5e9/charset_normalizer-3.5.3-cp313-cp313-win32.whl", hash = "sha256:b30e5496e453ac971bb17f5e096b84fbaae16d09e2613f6148ff528c08a54a0c", size = 185084, upload-time = "2026-11-23T02:44:38.431Z" }, + { url = "https://files.pythonhosted.org/packages/6c/53/c56cbbee8fc51fef0a8e775488c4ef5205047a190ad850c43ad4b2ae7b35/charset_normalizer-3.5.3-cp313-cp313-win_amd64.whl", hash = "sha256:cb18428af7399e0a6f7e3b45f110d57a1a47cf07fd4b3ce50e2366d99a38959a", size = 213792, upload-time = "2026-11-23T02:44:39.613Z" }, + { url = "https://files.pythonhosted.org/packages/b4/02/9c2209835e8767fefe1d91c22ae700bee5e6105e0e820debdf3e4fd07e86/charset_normalizer-3.5.3-cp313-cp313-win_arm64.whl", hash = "sha256:8b969f0309de905101bc3d2471c112e9ccbba711a7590b12d51f372b4163688a", size = 200777, upload-time = "2026-11-23T02:44:40.757Z" }, + { url = "https://files.pythonhosted.org/packages/9c/19/171fbc8735d20f22891d7f48ebb7ab5bd16e329726920d4c47ca6a520aab/charset_normalizer-3.5.3-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:c39a4fe28a16e8fa667c55c154f62c6c3cd9ca2491cca9f16330dd7360d05b76", size = 230746, upload-time = "2026-11-23T02:44:41.982Z" }, + { url = "https://files.pythonhosted.org/packages/f2/6e/dd550464337918ade1b01ff3f232f9f9c5374df2cc784044616e5e42d1ca/charset_normalizer-3.5.3-cp314-cp314-android_24_x86_64.whl", hash = "sha256:9c1bd8321a840729a6b2620774cf4000fafe66c54cac9064972a10c4f607794b", size = 244366, upload-time = "2026-11-23T02:44:43.197Z" }, + { url = "https://files.pythonhosted.org/packages/43/9d/0a283271f4c7857bb6669228fcc4c92e73b6b6029cf1762344eb9830628e/charset_normalizer-3.5.3-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:5f86753952f7de3abc7ce871f8239ce4e0d32a91c84d22f3a667e669907c3897", size = 224040, upload-time = "2026-11-23T02:44:44.437Z" }, + { url = "https://files.pythonhosted.org/packages/96/8f/f084960593eaa570230bd847c198531ea5d0df7580a9d43dfac48f746f62/charset_normalizer-3.5.3-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:581d6e7df9b58d34147e21efde42a480b5087fe54f31e42550c26321566ba1e4", size = 227968, upload-time = "2026-11-23T02:44:45.792Z" }, + { url = "https://files.pythonhosted.org/packages/de/f4/8a4dd59b77e505ce3fbfd27bf3cafedf27ef946bfd6b4c074f0d4a705fc9/charset_normalizer-3.5.3-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8231365b03b702b516aad35c9515694177ac31c9dc6240326f07308a4c45c708", size = 388599, upload-time = "2026-11-23T02:44:47.076Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a8/0fed9cde3b8197c99b0981bc53ee7f84cc38a3805a4c5f1c1003cda50588/charset_normalizer-3.5.3-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:ee9de080e8d6221bbe4ba2667367b1cee0f47a53f60ffc5e431b698cd2f2b214", size = 257076, upload-time = "2026-11-23T02:44:48.32Z" }, + { url = "https://files.pythonhosted.org/packages/ea/4d/3025852264de946fd2c559ea445bd8600c7b76ce9e0a9774e08ec243311d/charset_normalizer-3.5.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:61e32fdbf56f4cd25a1efa451c8b5fe886fc5e00143ccaacafdf21f301fad059", size = 240721, upload-time = "2026-11-23T02:44:49.495Z" }, + { url = "https://files.pythonhosted.org/packages/e3/7c/324b9b9354fb779d88ae14a3e5b8d16ab4e2c535fc7af609c647215a8c29/charset_normalizer-3.5.3-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:826d82356907350f345cf0aa744d43a69ac7948bd60f460f997cde86928beadf", size = 236682, upload-time = "2026-11-23T02:44:50.704Z" }, + { url = "https://files.pythonhosted.org/packages/2e/5d/ede4f860c14369e599b9eaea27277faa6b799e4205037dcdea9ba70482f9/charset_normalizer-3.5.3-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a312fedd182357f2c22f066d17dcd7413b6a205ee3d063d36950e94e3019d3de", size = 276116, upload-time = "2026-11-23T02:44:52.196Z" }, + { url = "https://files.pythonhosted.org/packages/55/04/156d80f0d51fb1edbb04969d5127fe34eff9721374cd4f02b822a4ea787b/charset_normalizer-3.5.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:249bf0b6f43985c33c83adbbab0ca71246ec24c82d960fa00c4ddb2cfed25db9", size = 273001, upload-time = "2026-11-23T02:44:53.499Z" }, + { url = "https://files.pythonhosted.org/packages/c9/53/2ebca72cbea022292180ee0a5cedb65c4cafbdffeee4142910bf70d0f454/charset_normalizer-3.5.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ea880ae1a692ae694c11bca7be74864614ff1a58bdfff4605f36d1956b4b1588", size = 254524, upload-time = "2026-11-23T02:44:54.678Z" }, + { url = "https://files.pythonhosted.org/packages/d4/32/fb3d20d2bb50071c6370d03c24fbd7fa7c49a5d4170d00a9029b6851c44d/charset_normalizer-3.5.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e34f591669498a03cd70993b0a79b9f0ef40c4e6f8232466bac33c42f0c15742", size = 242520, upload-time = "2026-11-23T02:44:55.846Z" }, + { url = "https://files.pythonhosted.org/packages/01/0e/9f259d7b12c7d707c2784deef221cef368b10a37b5dc56bc49f818116ddf/charset_normalizer-3.5.3-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:ddea089587432e3df6771a4a405ef249cc9727f7becb1de3f00ab571b2432002", size = 240962, upload-time = "2026-11-23T02:44:57.08Z" }, + { url = "https://files.pythonhosted.org/packages/b4/b0/d1916a27c54a67730104da1fee1218d3a476954b3ed2e47a1c28569ec720/charset_normalizer-3.5.3-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:f160f03e15bd1e3c35db9bfc20c42ff83155d37f9b0c79806cb10051ca725f13", size = 276468, upload-time = "2026-11-23T02:44:58.303Z" }, + { url = "https://files.pythonhosted.org/packages/17/96/c72352c6bdd9251e979731bdee97fb88dcb9574b0baf9df4d519dc124546/charset_normalizer-3.5.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:6651fecdac146ecfa52700e02a5fa3b3677bddf5fced4983b43e904244de3f6a", size = 254535, upload-time = "2026-11-23T02:44:59.853Z" }, + { url = "https://files.pythonhosted.org/packages/25/d8/5d22ba93705c0ae58ea135f3e4a914953348cf6e50d4a40d638dace152e8/charset_normalizer-3.5.3-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:45aa4ccf5a6caba138dd0f8bf36fa3e26654585d534881b62ce5e4fea2487772", size = 274514, upload-time = "2026-11-23T02:45:01.002Z" }, + { url = "https://files.pythonhosted.org/packages/7a/40/997607e03b4a79f3ac2074f0519bebe35b88b874139c9a98e96e0711bfac/charset_normalizer-3.5.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9eba4613d45b49196af04a5cbadfc5e9379ba94aac85184b72cb1107ad31af0d", size = 258968, upload-time = "2026-11-23T02:45:02.207Z" }, + { url = "https://files.pythonhosted.org/packages/d7/1b/c3a6b94a46302aeb20e5cbbcefbb18cfec59abf235f031409bd15f555ff4/charset_normalizer-3.5.3-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:2e7fbd98443f28a5ed8004f0b058edcc4720a3d344adf007c0b7f1adbff2f59f", size = 145526, upload-time = "2026-11-23T02:45:03.786Z" }, + { url = "https://files.pythonhosted.org/packages/fd/82/0e4c6c596fd0ec4615255d05cab0c8fa42cec62e3b2be51bdcabab4a0215/charset_normalizer-3.5.3-cp314-cp314-win32.whl", hash = "sha256:d8f85e019c9f08ec134648a378ddd3f6f073c1e4b5ce9bdacd9a9e7b60749cd2", size = 187860, upload-time = "2026-11-23T02:45:05.079Z" }, + { url = "https://files.pythonhosted.org/packages/a0/4e/0d31216be12c3146dd282b043957805d4dda8806cd7b99c90273d251f0f2/charset_normalizer-3.5.3-cp314-cp314-win_amd64.whl", hash = "sha256:b66a0e045cf859d7418f26a554509b65f21ebb6d90a95152460781939e8264f4", size = 218705, upload-time = "2026-11-23T02:45:06.207Z" }, + { url = "https://files.pythonhosted.org/packages/68/5c/8c8f2202314b8918d51146ab2337af9721c9e7c74867c86f625556f657b9/charset_normalizer-3.5.3-cp314-cp314-win_arm64.whl", hash = "sha256:b8fc4fe56992b089d6177021fe6db641321bb2bc2fc7a1abf815c29a80ca2137", size = 205681, upload-time = "2026-11-23T02:45:07.379Z" }, + { url = "https://files.pythonhosted.org/packages/a8/52/01e5da4f7d4d10195f745c37b0daacd83a0fe112e9b6d959663a775ce489/charset_normalizer-3.5.3-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:6c80b4e83e2fbddd25fe27804cdfc45ef71bb387522caa575af42118d72dc970", size = 413919, upload-time = "2026-11-23T02:45:08.58Z" }, + { url = "https://files.pythonhosted.org/packages/67/49/277767bc060dfcb0788103acd67ec3831cbcc671f5a7b12b4935e733e09a/charset_normalizer-3.5.3-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:7a7e5bb8974842ad747d4a2b9fb928f84c3cdbe2c2fd7e405197fc1a1badaeaa", size = 260695, upload-time = "2026-11-23T02:45:10.005Z" }, + { url = "https://files.pythonhosted.org/packages/e1/33/f017126fd88ad2e39d947044af196b28dc91633f23dded8754ae944e2f03/charset_normalizer-3.5.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:28ba8e6361e0f319641707484994096ceb77e05c29eaad2919756218c0c89001", size = 246771, upload-time = "2026-11-23T02:45:11.143Z" }, + { url = "https://files.pythonhosted.org/packages/32/0d/c147965a1989b0e85f5aabf29a309ee7deb34ac7d89442c0fd51c8055981/charset_normalizer-3.5.3-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e405cce4170de1fe520d9a92de9d7ececc23dfcf6888c62ab608a21be50838eb", size = 235360, upload-time = "2026-11-23T02:45:12.501Z" }, + { url = "https://files.pythonhosted.org/packages/55/f9/48509fa40ce22ce10497dd6689818b6676a482d7b3eaad02a558744d08c6/charset_normalizer-3.5.3-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:81132eaffa984f0a399233df4cd383caad18e8cadc6c24c568cf9324732a9768", size = 273351, upload-time = "2026-11-23T02:45:13.717Z" }, + { url = "https://files.pythonhosted.org/packages/8e/9e/3090f8b88f300b71c5d45bfe214f7a9e156de76cf37d12345338f1b63f5f/charset_normalizer-3.5.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c43d9737c3b85ccd16b1862b1e7aa5c4bf30a6033068403713c0a2bba5bda979", size = 274795, upload-time = "2026-11-23T02:45:14.991Z" }, + { url = "https://files.pythonhosted.org/packages/e1/93/171bf6dd9bfbbc21be219fdab5213bb7ee8a8edff9b4acc982cb905e5687/charset_normalizer-3.5.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:94c9d5d91c16554f6397b823d9e47181ba100d830ab16b5d720adc229e17b2e2", size = 254931, upload-time = "2026-11-23T02:45:16.454Z" }, + { url = "https://files.pythonhosted.org/packages/aa/6a/e5a41dbffdc064c635b487debd32944e19777e6d938ebbc88fca1996e231/charset_normalizer-3.5.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:0c0fe07631dce6dae788a59c20ed927adc6feeb2d9ed440747eb367d89822a45", size = 249689, upload-time = "2026-11-23T02:45:18.096Z" }, + { url = "https://files.pythonhosted.org/packages/d5/3c/0b7869da44ab5fbae135df0f9a12a9325c42e37c221353dc194a01b3b3df/charset_normalizer-3.5.3-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:0ca25f1b1167e9fb94d93d3708df0b631de241bf8440947b0cb9f8c4cb66fed0", size = 242935, upload-time = "2026-11-23T02:45:19.215Z" }, + { url = "https://files.pythonhosted.org/packages/4b/59/c6fd64ab23eb58bd42e940be294864b7d197ea2a2bebe572f3e6600c2d34/charset_normalizer-3.5.3-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:fcb17f1d40c38912a2cdb56ea47aadac3527cd0b06fe24f3a0c4896febbea063", size = 275394, upload-time = "2026-11-23T02:45:20.373Z" }, + { url = "https://files.pythonhosted.org/packages/c3/d6/208641f89b848dbe842b37175f9cbd56183dedca850377c5d03ae77a5215/charset_normalizer-3.5.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:39e019884c8f857393df954d35f42bf99c5ab85af226fe74d1410188c6fec31f", size = 255552, upload-time = "2026-11-23T02:45:21.529Z" }, + { url = "https://files.pythonhosted.org/packages/f2/a0/04609cb3fe13091be9c8e24c75b55e12cb35882db5d4377c86c58dd09913/charset_normalizer-3.5.3-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:e282983b8def5ada758fa1f18bf9060bb8ce6cdd73be32f62a2de59820d3286d", size = 273420, upload-time = "2026-11-23T02:45:22.736Z" }, + { url = "https://files.pythonhosted.org/packages/2d/45/c8c27b6e00e6a39175a5b7b0df73d787a84d320012a882647f8c81ce915f/charset_normalizer-3.5.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cbd09b22b340f846671e79e8d832167fac60c1884be4c71fd667211486a3b58e", size = 263761, upload-time = "2026-11-23T02:45:23.812Z" }, + { url = "https://files.pythonhosted.org/packages/d0/c0/51435f05b16daf627d5525de00334f869707aead4e9214e004809b7840f2/charset_normalizer-3.5.3-cp314-cp314t-win32.whl", hash = "sha256:a8f92cc9080bff47555c79b88e7fb8655438ce3bcf29c5f01ed2ed5efdf174a4", size = 200709, upload-time = "2026-11-23T02:45:24.92Z" }, + { url = "https://files.pythonhosted.org/packages/63/14/93634f18a4d3f17b90b0f40852ee9ef45834dde21112f7be5b28c25062ad/charset_normalizer-3.5.3-cp314-cp314t-win_amd64.whl", hash = "sha256:1a34385837db59d5de814c9f1e0f4157b571f9ce0eabdaeace410aa93bf5df62", size = 218684, upload-time = "2026-11-23T02:45:26.194Z" }, + { url = "https://files.pythonhosted.org/packages/57/78/f70f630a2a6af3a09fb82403425576b3c1c366c4e766bdb624b56c4a3d24/charset_normalizer-3.5.3-cp314-cp314t-win_arm64.whl", hash = "sha256:a094178c51530c9ebd1775e72d160af0eac4be244fb06ff1b6f182128c71903c", size = 209276, upload-time = "2026-11-23T02:45:27.794Z" }, + { url = "https://files.pythonhosted.org/packages/7d/63/99fe455c382b9ae254baa0eac2b252d83d174d42ff39557083cc6d1a6e85/charset_normalizer-3.5.3-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:f7fb9a3275f1a1528e542a0f5a3d2c89fcaf68e797fc5c6530434cbd92a852c4", size = 388433, upload-time = "2026-11-23T02:45:29.061Z" }, + { url = "https://files.pythonhosted.org/packages/d3/0b/2cca2599ccb85cb31c60d8d19fcd9f89bc113696b2be2fd774288bc78691/charset_normalizer-3.5.3-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:ef8b925f2b331a1f17d6fb32625e09fd571cf41844f578379f934dab0067cf0d", size = 257397, upload-time = "2026-11-23T02:45:30.196Z" }, + { url = "https://files.pythonhosted.org/packages/e2/fc/7f46bdf26bed47cee8f053dda462b9e00dc56cf767f99a88b077ebfdf30b/charset_normalizer-3.5.3-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:390ef7c7e018c0abb8c0ec2d28ee137567ff50c3706facf6d115cac832ac993b", size = 241315, upload-time = "2026-11-23T02:45:31.352Z" }, + { url = "https://files.pythonhosted.org/packages/8e/55/a6be3d284ea45451d700d1fb58fd9db7155dbbfff7799b7c6351e419c528/charset_normalizer-3.5.3-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:106b9d0438e2ff0a0e8ebd869273fcb3640af28323bba8651c714c57efb38e51", size = 249109, upload-time = "2026-11-23T02:45:32.508Z" }, + { url = "https://files.pythonhosted.org/packages/57/5a/5cd92437895d67c77add5adebc512a00fe06b7146dd679cdb8b146b94a9f/charset_normalizer-3.5.3-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6bfbbb9414dd0f5b81c259deb7e50b4b44e65e05879eee482351bdabed49d7f4", size = 276158, upload-time = "2026-11-23T02:45:33.752Z" }, + { url = "https://files.pythonhosted.org/packages/02/b3/18750413345158ae3223fb083c68b497756f7e5b187e216a2b30e51aab70/charset_normalizer-3.5.3-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:11ad35a0b856ad8bbd0c9e900c069461a4661694714aa17b6e6e2e8621e1c373", size = 273314, upload-time = "2026-11-23T02:45:34.936Z" }, + { url = "https://files.pythonhosted.org/packages/54/b6/d790397b7742c37379942d46816287d90b102aded0f9d48b6418d96403d8/charset_normalizer-3.5.3-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:6118055f4ad0d94e016eadbb86caed9caf2c9033631ed70964ba631c1336984f", size = 261077, upload-time = "2026-11-23T02:45:36.46Z" }, + { url = "https://files.pythonhosted.org/packages/a3/da/fd1e0c83475fe7f8dfbf4c0f9308a122963972a81a5507351f6079a47770/charset_normalizer-3.5.3-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:a09ca76391f6e17b12d55c1068b4b5f8f6c9b44b432d936075372fa12782292d", size = 243097, upload-time = "2026-11-23T02:45:37.891Z" }, + { url = "https://files.pythonhosted.org/packages/9d/00/a8e73fd75e0f6bc5127bb49065a585fcc12b0bb9643b54b25b20375e0782/charset_normalizer-3.5.3-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:acaa0e100f39287dc5d13de96e33ba0786f1cdfb5b4ca28918913ab0eec3af72", size = 252349, upload-time = "2026-11-23T02:45:39.407Z" }, + { url = "https://files.pythonhosted.org/packages/06/96/dc3e6ce15bf01c3e3a98769fb3cd2bda57661521eba22e2b9f3b55e4ee3b/charset_normalizer-3.5.3-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:a3f4044dd5d2f7b958be6b9903cb432e6a0fd944d673707ca5cab68137d0592c", size = 276520, upload-time = "2026-11-23T02:45:40.608Z" }, + { url = "https://files.pythonhosted.org/packages/67/65/437f58102ffd405f05b7e00e6ee1fa9b97536e4fc71b518b917b847cf1db/charset_normalizer-3.5.3-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:d1b7a3fe4cf679eb3870b91b86b8ce12cacd5cf4d74bc114864a5cd65319ddac", size = 260666, upload-time = "2026-11-23T02:45:41.736Z" }, + { url = "https://files.pythonhosted.org/packages/72/06/5113ebc19322267ab243a0cb972cc03af89e31665a6318f711cb410b2906/charset_normalizer-3.5.3-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:323d5cf6df3ea724afcc3bfb07c73be06d2e8200a8b6b37979a300ae1e7836d0", size = 274614, upload-time = "2026-11-23T02:45:43.227Z" }, + { url = "https://files.pythonhosted.org/packages/ca/b1/41062ab95a6b6806ba9b175dfe33496a5e8b3a9b1cf50096fbf53beac472/charset_normalizer-3.5.3-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:67bb767a8de7a2b1164c74fdbe5cdc32b9c15d7142efd9a6dc77ff63da94e846", size = 259557, upload-time = "2026-11-23T02:45:44.491Z" }, + { url = "https://files.pythonhosted.org/packages/6c/4a/9ea96a756aa9884b6bd4bbdcd0293c23cc198b0a986831078593a98d61fc/charset_normalizer-3.5.3-cp315-cp315-win32.whl", hash = "sha256:d93403a13c8f6f2d027185d90ab695e81d95e3ebd000f0078e201a1c3159d4d1", size = 187747, upload-time = "2026-11-23T02:45:45.711Z" }, + { url = "https://files.pythonhosted.org/packages/4b/16/c6cdbdf7f3b92c43fdacc074202db46e4f85af1be7fb2fa3fc015167c8a8/charset_normalizer-3.5.3-cp315-cp315-win_amd64.whl", hash = "sha256:2978c799237eb66619d8951d2ab7efd317414cb6682160e05614ce1c8b5c905f", size = 218469, upload-time = "2026-11-23T02:45:47.225Z" }, + { url = "https://files.pythonhosted.org/packages/73/4e/10d9b92b827dab4e333af2e3bfb4955b5504fa04953e7d83862383ac844b/charset_normalizer-3.5.3-cp315-cp315-win_arm64.whl", hash = "sha256:9a6b95b1737f9b5942c35676c52db0c302d60fa806efde3fc2d9f54247ecf4be", size = 206254, upload-time = "2026-11-23T02:45:48.429Z" }, + { url = "https://files.pythonhosted.org/packages/34/86/e0945f37d12630d50e96ba7d8d6935efceb168fc4a58fe26b2f4b80972f5/charset_normalizer-3.5.3-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:06d07272f70d9880fba32d4876e966ae4dc9961134bc989066a0901509dfd8cf", size = 411657, upload-time = "2026-11-23T02:45:49.713Z" }, + { url = "https://files.pythonhosted.org/packages/49/3e/d4c3e4f3b4a63cbdb1215746d2d9e87d890d36a4967a53e50b04d5e4e261/charset_normalizer-3.5.3-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:da606e3015dbd4b9a31c0468898a0c4c998846197ddfda78308821dc8c9e9be3", size = 260078, upload-time = "2026-11-23T02:45:50.953Z" }, + { url = "https://files.pythonhosted.org/packages/3b/43/91b08f37f5561e4e356533f103fb3c60367378871ee730480dbf05571e3e/charset_normalizer-3.5.3-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6423accb6ecd1456bf824bbac98ba919398523a69ee5f1680dd1da88769de866", size = 246616, upload-time = "2026-11-23T02:45:52.141Z" }, + { url = "https://files.pythonhosted.org/packages/5a/25/29ea27a18f5b84baf2c12b9ec5ecd2f44770ba11fa9431f736b641a47c5e/charset_normalizer-3.5.3-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:ad1becd776f5a41a4d91cb9ee51778f4fd687ef15e4919779e00a33c6cff6948", size = 245190, upload-time = "2026-11-23T02:45:53.322Z" }, + { url = "https://files.pythonhosted.org/packages/81/d0/ab1609490f8bf70a2de391abf6897a22410ea6639c5c62e5085b4791ca0c/charset_normalizer-3.5.3-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7fdd11094a0b07bce306b359fa7311c71d93466d967b3b345f2e9f03d8b2c959", size = 272663, upload-time = "2026-11-23T02:45:54.53Z" }, + { url = "https://files.pythonhosted.org/packages/a9/34/d898562f7733b7479aacb9b1bfa7d3953472a5ac2d7799c5b7cc10b15860/charset_normalizer-3.5.3-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:87d5a237d6531c654e7b9b319be9ba7e368665c466e02a03cfd4d3d77730782e", size = 273912, upload-time = "2026-11-23T02:45:55.697Z" }, + { url = "https://files.pythonhosted.org/packages/34/13/952195e0a1eb774cfacdac376ccbd45ee5f062ff1ebbce13f16a3cd61f56/charset_normalizer-3.5.3-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e4a0f2adf29a69dd8fe58e42bb191f3c87067b05fcc63279983e8c9ce5092abd", size = 262197, upload-time = "2026-11-23T02:45:56.819Z" }, + { url = "https://files.pythonhosted.org/packages/7f/64/57a0b74ef74e8fbc72eb534074d927b6cfde7c636d7a130c01ea363c38f4/charset_normalizer-3.5.3-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:643724071b01cc0369026e259850791212cc187c6031d0e930abcd253f128e0c", size = 249293, upload-time = "2026-11-23T02:45:58.069Z" }, + { url = "https://files.pythonhosted.org/packages/03/2d/c85f799904ba58873292482777877ad7f8de59432acd19798bcd333dd379/charset_normalizer-3.5.3-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:94b595e64bc2927f679774de50df340b7828dc1c07c99149ba7c2d0828dd8bf3", size = 253017, upload-time = "2026-11-23T02:45:59.293Z" }, + { url = "https://files.pythonhosted.org/packages/3b/b3/094707e46822715358296d9240b5bda6d9c3d22492dc9e90a72b2e32d1cf/charset_normalizer-3.5.3-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:e86a27ab632d2e888c22b79263864eaff8b7dea9e87328a9bb0ea04eff24786f", size = 274884, upload-time = "2026-11-23T02:46:00.405Z" }, + { url = "https://files.pythonhosted.org/packages/29/ea/86c082d940bd103d9c3a55b426c0c63d7042c2d43c1c35afd8cb6470b735/charset_normalizer-3.5.3-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:48f7c7f537246bb3af2b3139f44716a30b21e78c2fd1cff0f3e392fbd55d8044", size = 262028, upload-time = "2026-11-23T02:46:01.547Z" }, + { url = "https://files.pythonhosted.org/packages/96/5d/b41c750bda9b9eb354a802b4c399c0960f33b06555d1dd265bd29eade5cf/charset_normalizer-3.5.3-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:085a5d1f49eaf96596d79494fcab18d9a32db6e345da15d6debfc90110b20679", size = 272487, upload-time = "2026-11-23T02:46:02.747Z" }, + { url = "https://files.pythonhosted.org/packages/cf/08/d1968a27a29aa0338329dcf0462272a4f4335e5255d7a7f5bea9689d5c84/charset_normalizer-3.5.3-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:6c8abe7d59bbc891e5080b8b142c36db93154f840c4baf7c83ad6273a1a15397", size = 263202, upload-time = "2026-11-23T02:46:04.239Z" }, + { url = "https://files.pythonhosted.org/packages/b3/77/5abae54c1eeba13ace198119b514ff66c6b07ba0fe8b56f4fb96a299a651/charset_normalizer-3.5.3-cp315-cp315t-win32.whl", hash = "sha256:02b1abf64742b2d0782172cd2542616e462c201c829c23aff833390babe2967f", size = 199993, upload-time = "2026-11-23T02:46:05.377Z" }, + { url = "https://files.pythonhosted.org/packages/36/04/171d1d5352713792d8eebc14ff461625cb6cb0517bf57e0c4e95c1663480/charset_normalizer-3.5.3-cp315-cp315t-win_amd64.whl", hash = "sha256:dfbde696fb427301ec40cd82b8eec0b528e44c6af8239f33ede2b2552d9a085a", size = 217514, upload-time = "2026-11-23T02:46:06.784Z" }, + { url = "https://files.pythonhosted.org/packages/5f/5f/cb8485f62fec625bebab015874df0eb9d8332015b4462fd1da41d1ab1c54/charset_normalizer-3.5.3-cp315-cp315t-win_arm64.whl", hash = "sha256:aa9390d89822dd06f9920ae3038819cb121643a72f4753b2eee1a79b2f1215f8", size = 208602, upload-time = "2026-11-23T02:46:07.978Z" }, + { url = "https://files.pythonhosted.org/packages/64/57/146cbf75a34eb50a27ca6daf4841a4a13a0726fa05db6f7fe97c8f14f383/charset_normalizer-3.5.3-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:84356c7b7ddf090e3e4692cb99fc820e6189b5f6662ca7e8589f41095cc8efca", size = 376114, upload-time = "2026-11-23T02:46:09.155Z" }, + { url = "https://files.pythonhosted.org/packages/5f/02/b01868added37f27a6b0fd29e7fa19d0ae52b3fdbfc6fde6b9c98ef377ec/charset_normalizer-3.5.3-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:26c6ad87bb79628954b52f8f7b9e18ab5cd9667546712ded9689fb7677e630d6", size = 234407, upload-time = "2026-11-23T02:46:10.528Z" }, + { url = "https://files.pythonhosted.org/packages/9b/9c/a8dddbe4ca722fac44bcbb17c08670bd9f1e9d26a481f7129aa2215eff80/charset_normalizer-3.5.3-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d4e7ecaa25f0dae672ac783c2e5aa9054a62e011749d64ff47b887af360a3e82", size = 222474, upload-time = "2026-11-23T02:46:11.939Z" }, + { url = "https://files.pythonhosted.org/packages/3f/28/b9d955132ca12845bf4d498cac4cad731d88f7dffcfe9ab26182ba19b9b9/charset_normalizer-3.5.3-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:ba26e4d073a4f7f2594676f2ff20ab80a7f03332b81c3f9964e9e53bf2305329", size = 234588, upload-time = "2026-11-23T02:46:13.175Z" }, + { url = "https://files.pythonhosted.org/packages/75/87/5c957d23953540fd53f8bf99f25aca4a73ffaa2621e0c199fa33bea68670/charset_normalizer-3.5.3-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4831fb33e98e92140fa17d4d673a9f49f9c0ddd056115b722858793e4b86b0c5", size = 264230, upload-time = "2026-11-23T02:46:14.634Z" }, + { url = "https://files.pythonhosted.org/packages/2e/33/94e72d80177dfc1c68d4250bcfc0ac81c7fffb6fb7692eaba1050839c822/charset_normalizer-3.5.3-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1714ff1ba001da5241a585fbd17a7742a61ad34efb4be8404aca5679f51e53ea", size = 259027, upload-time = "2026-11-23T02:46:15.803Z" }, + { url = "https://files.pythonhosted.org/packages/22/52/2c903fb577eb4fecd1c6e0f426daa4f0af5ae2e2b453985e1995317deeb6/charset_normalizer-3.5.3-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8c4dfcd3269f13dff7f29f9c332d54a4a21f17be818b49e769e111befd4d39e6", size = 252786, upload-time = "2026-11-23T02:46:17.024Z" }, + { url = "https://files.pythonhosted.org/packages/a9/6b/f8c6680edbaa937982c3f0e9a9cbc7634135bed7a6633cbccbdefd8e64b7/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87f7d6c595465a25d33fa3d5215a571a98c4cad00ead3ad18ebfb62adb3d3e6e", size = 223576, upload-time = "2026-11-23T02:46:18.245Z" }, + { url = "https://files.pythonhosted.org/packages/37/24/5ca15b50e452d0b689c152b27ff525b417dde009f0daea1805767a683a3f/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:7c313b46730b4a68bb31450973467313b2c496fefa42ae316b86c186cba74613", size = 235893, upload-time = "2026-11-23T02:46:19.448Z" }, + { url = "https://files.pythonhosted.org/packages/e1/c7/4857928626613d6991d3cc045de5d101ebf04dad1b5786facd5bd9d843e3/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:d313494077f849d8199f36166947785da1eeb36335fda15fde2e8f801ef271b6", size = 263887, upload-time = "2026-11-23T02:46:20.811Z" }, + { url = "https://files.pythonhosted.org/packages/4b/25/c6ddeafc6301f7675089d093219f923db0311bd99c7c6e21cd6f10e97884/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:c08e06fc69750827d7ccebba63ebc97a85e479cd5c9dbdb80f5e08a77b774fdb", size = 250628, upload-time = "2026-11-23T02:46:22.044Z" }, + { url = "https://files.pythonhosted.org/packages/f3/1e/2536f55939d911bd638982aba11a2a26d8b5a49926d2d93e3d6cd236e180/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:29ac44f5878142128ffe4fa7e041ddc4cc5fafe43983245b9a141908c40b515d", size = 261092, upload-time = "2026-11-23T02:46:23.382Z" }, + { url = "https://files.pythonhosted.org/packages/3a/fe/aa2706988f2e4e46e79a488383dfd2f4d166728e046d8ae29cf8466d38e2/charset_normalizer-3.5.3-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:3e8da696ef1935a019c10ec16555a062183ddf6d5901e296edeca4b2a8f84e1d", size = 236268, upload-time = "2026-11-23T02:46:24.607Z" }, + { url = "https://files.pythonhosted.org/packages/6a/79/9264b6a1411dcaf0daa0d58e6915545ddc8b056b53ece56375bcf9776c88/charset_normalizer-3.5.3-cp37-abi3-win32.whl", hash = "sha256:4ff5e27478681ef1b13b036baaf9beaf9b4c6990e903c752ad3b8764692c6d6c", size = 177808, upload-time = "2026-11-23T02:46:26.059Z" }, + { url = "https://files.pythonhosted.org/packages/a3/a5/cc188879ab8e8a36d295f888335f0a2875e39bcdacc6fe3207427c14036f/charset_normalizer-3.5.3-cp37-abi3-win_amd64.whl", hash = "sha256:a5a7e0326566759f9a7bc44f4b9a179cc40a297e09e759b0bc7c848c06347527", size = 200667, upload-time = "2026-11-23T02:46:27.221Z" }, + { url = "https://files.pythonhosted.org/packages/d5/a3/4a6047c40414f170ad09a6d44c1a0663914924619304817c2e33d19fae75/charset_normalizer-3.5.3-cp37-abi3-win_arm64.whl", hash = "sha256:e4f85c34f9be32ec5568a0668fb8bc029d3e729285fb8fccc38695e185379a9b", size = 290628, upload-time = "2026-11-23T02:46:29.06Z" }, + { url = "https://files.pythonhosted.org/packages/d2/0d/07ab8eb9b7015274353eac2add4067bde1ab1b51912bbae505392905eedd/charset_normalizer-3.5.3-py3-none-any.whl", hash = "sha256:96e268b0cbda016ac519513294fcd17032264085b600abaac58b93049477e132", size = 68878, upload-time = "2026-11-23T02:46:50.665Z" }, +] + +[[package]] +name = "click" +version = "8.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/37/edbf1b0707709013c0cf2e8317e03d97ed29bf4cac709fe328904ae92a38/click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4", size = 399151, upload-time = "2026-11-06T17:37:01.021Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/7d/164b7ffc8624fe9efb4221bf9af485d5c1e41b9ae118045d2b6dc5457d8b/click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37", size = 126163, upload-time = "2026-11-06T17:36:59.287Z" }, +] + [[package]] name = "colorama" version = "0.4.6" @@ -11,6 +199,39 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "ghp-import" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d9/29/d40217cbe2f6b1359e00c6c307bb3fc876ba74068cbab3dde77f03ca0dc4/ghp-import-2.1.0.tar.gz", hash = "sha256:9c535c4c61193c2df8871222567d7fd7e5014d835f97dc7b7439069e2413d343", size = 10943, upload-time = "2022-05-02T15:47:16.11Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f7/ec/67fbef5d497f86283db54c22eec6f6140243aae73265799baaaa19cd17fb/ghp_import-2.1.0-py3-none-any.whl", hash = "sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619", size = 11034, upload-time = "2022-05-02T15:47:14.552Z" }, +] + +[[package]] +name = "griffe-inherited-docstrings" +version = "1.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "griffelib" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/cb/da/fd002dc5f215cd896bfccaebe8b4aa1cdeed8ea1d9d60633685bd61ff933/griffe_inherited_docstrings-1.1.3.tar.gz", hash = "sha256:cd1f937ec9336a790e5425e7f9b92f5a5ab17f292ba86917f1c681c0704cb64e", size = 26738, upload-time = "2026-02-21T09:38:44.312Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/16/20/4bc15f242181daad1c104e0a7d33be49e712461ea89e548152be0365b9ea/griffe_inherited_docstrings-1.1.3-py3-none-any.whl", hash = "sha256:aa7f6e624515c50d9325a5cfdf4b2acac547f1889aca89092d5da7278f739695", size = 6710, upload-time = "2026-02-20T11:06:38.75Z" }, +] + +[[package]] +name = "griffelib" +version = "2.4.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/36/e2/0f5d8ed08766bc6dcd3eebf5a6623d83cbca33a6e4c90aef57156ce745ad/griffelib-2.4.1.tar.gz", hash = "sha256:40c028dd2e623f464423f0e11e3c553158f1cf4f1368239a370534d73e1407ff", size = 245153, upload-time = "2026-10-22T11:20:03.705Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/02/1156d5f5307f573b901b14373848b84e69ca6cab09169b8cc97d16a181f9/griffelib-2.4.1-py3-none-any.whl", hash = "sha256:76bc562f936ad1ce198d2cf6d0731bd5c92a7d934b69ef828ef22ee0ffdb62ce", size = 172983, upload-time = "2026-10-22T11:19:59.843Z" }, +] + [[package]] name = "hypothesis" version = "6.170.15" @@ -104,6 +325,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/03/f5/410ff24a49dd645f651732f45e466cbb73f4bb73d1c54eaa5a07b832b0a2/hypothesis-6.170.15-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:d25e9a3f92e9f824bb110679506ece2b8fd7d093f1fa7d819ca46278a681a1f1", size = 692539, upload-time = "2026-11-06T09:53:30.812Z" }, ] +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + [[package]] name = "iniconfig" version = "2.3.1" @@ -113,6 +343,278 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, ] +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "markdown" +version = "3.11.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1c/ff/8644daa33bfdf552c9cfec8d1fc2c690f57a347808f62c406ac6557329c2/markdown-3.11.4.tar.gz", hash = "sha256:c911a757f33d64a2578bed2d20c57e007b2aedd8a67bceabd593b31143d54ead", size = 505340, upload-time = "2026-11-25T16:26:12.029Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/61/54/188fcc228c71a4ae33244008af08c2e7b1945b657390f56d82dfbe4059f0/markdown-3.11.4-py3-none-any.whl", hash = "sha256:2e30b19cead1968f391206e184ca67dfe6805c2eb8f383fb07b4dc90f8288075", size = 119551, upload-time = "2026-11-25T16:26:10.692Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777, upload-time = "2026-10-02T23:07:22.29Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/55/18dbb4778b30ada5ce071608503cc3edc9e14e13d868c17a6d178fc30f7a/markupsafe-3.0.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9e25feb9e330b63edb0278a0acdf85e50d0cb0fbf49c3084abbe4e24ae195346", size = 11520, upload-time = "2026-10-02T23:04:36.299Z" }, + { url = "https://files.pythonhosted.org/packages/6c/14/0b05f79b4733e264a18d08fe08fa1df7347630ff32a6cb82180d9dccec55/markupsafe-3.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7d3391b2188d18737cb2fa147028b1096236eaa7e156446c650a489fa2cadc91", size = 12063, upload-time = "2026-10-02T23:04:37.291Z" }, + { url = "https://files.pythonhosted.org/packages/ca/3a/63ba10b6c1463216b3e4df669a9f0e5a3b0c3071557d2e8229e3968c79fb/markupsafe-3.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849dd2bb0e5e4ab2b71c7191726a4a8d5aa8a610daa584728cbee0b710ddc4ef", size = 24321, upload-time = "2026-10-02T23:04:38.262Z" }, + { url = "https://files.pythonhosted.org/packages/1a/2e/5f015261b76ad633d187ef6f388b413aedd64a8773c4df59e530a0be5525/markupsafe-3.0.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:befb4158af32106b9a93db8d6d1d1cbbd418c0d5aca0cabb7b1780abf0c89169", size = 28845, upload-time = "2026-10-02T23:04:39.295Z" }, + { url = "https://files.pythonhosted.org/packages/33/cf/26e594b26be40c2f1fec63ccf8a8b99d0335a5b2cbe84835c7d82a994375/markupsafe-3.0.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:71f88e749ea29f67f21f3b36433c1dc54c7729ed2a6d9e2da2e0d9e0d7b224eb", size = 24701, upload-time = "2026-10-02T23:04:40.348Z" }, + { url = "https://files.pythonhosted.org/packages/81/a5/a513b76c139a3915b43404324e55c0b7979ae4f0d39eb6f075b0282e90a8/markupsafe-3.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6da83a088f8ef93b2d483a8232a4dbf4d69d3d8496b568a03c56becac43e1808", size = 22961, upload-time = "2026-10-02T23:04:41.372Z" }, + { url = "https://files.pythonhosted.org/packages/46/cf/4c66192c100b4542bcbe392ae06696b670f66927be3ac38a213234778ff9/markupsafe-3.0.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8f0fac8b13d14bb06c68195f849371924ae53dd7b1c00fed24650f704383b692", size = 21920, upload-time = "2026-10-02T23:04:42.429Z" }, + { url = "https://files.pythonhosted.org/packages/cb/17/ac3662678bfbad649893117ada2ba44dc30bf56884e84f13154a792b10f1/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4a7cdc2a420ca01058182da4253329764d4bfa055564d1eced90e6ba1e8b1d3d", size = 23726, upload-time = "2026-10-02T23:04:43.531Z" }, + { url = "https://files.pythonhosted.org/packages/f7/af/fe47cee339180a69ebca3c57fb3483d0f5cbd1e8337d1871fb1d9c1aebee/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:83b3944fea42a8400edf92fd1770fb8d0d4f7de651353bd2d8525a92dba69a21", size = 22539, upload-time = "2026-10-02T23:04:44.618Z" }, + { url = "https://files.pythonhosted.org/packages/12/32/d55440ba140442800e02d799c9cb5ab597bf6ebdb1177b5ea39a11f797bd/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8138eb83940ec7299024d92d4dee45f601b9e6c5ffde9d25f4e35e326203c707", size = 23963, upload-time = "2026-10-02T23:04:45.656Z" }, + { url = "https://files.pythonhosted.org/packages/50/9d/9c86042cb364c2ad4c971e6d1247929effd25f714cd7ee11b05e6316445b/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:811d02d5122171c1941357efd8f9bf4ffe907b7f0a1a4e729a880e4be3f46e3e", size = 21506, upload-time = "2026-10-02T23:04:46.671Z" }, + { url = "https://files.pythonhosted.org/packages/75/ef/5b824f03ba40c3b3652b6272d083d2fc4fcdd440de519a3a39ba2c3e7262/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:50b5bedc9ed8a94fc8857a42ef4f84a81ea88f8d4f05dc8705fb23ee6d8dcca7", size = 22955, upload-time = "2026-10-02T23:04:47.698Z" }, + { url = "https://files.pythonhosted.org/packages/1e/e8/44cfcb5ea40e5e43cec7793ef90704ed0c475280839076c4345757eb8e59/markupsafe-3.0.4-cp311-cp311-win32.whl", hash = "sha256:2e5a7cd7fdd14fcb1ae5d7d8bf23d24fbd1daefd1fbca2580132e1ea75f098b5", size = 14094, upload-time = "2026-10-02T23:04:48.788Z" }, + { url = "https://files.pythonhosted.org/packages/91/89/f2b509f7bf79352e40117824c1070dbeafd4df67031d3fa98165a3134228/markupsafe-3.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:fdb4ca07ab75ffadab4a8b135ad59cdbb3156b99310f3d565370da74a15d6bd3", size = 14328, upload-time = "2026-10-02T23:04:49.801Z" }, + { url = "https://files.pythonhosted.org/packages/2b/5a/ccf22672a0f64dc682306e288f0dabcb06c7a201f3bb6e6cbf86d9e8ad03/markupsafe-3.0.4-cp311-cp311-win_arm64.whl", hash = "sha256:569d65055d367e3dcdf30c3f41119467b73d9ee9faf332bdf40402644f5ac08e", size = 14188, upload-time = "2026-10-02T23:04:50.847Z" }, + { url = "https://files.pythonhosted.org/packages/81/09/4c59d56b8461ae8eb0d8ba34bb25b7e618547044679d58a82ef9b2479fc1/markupsafe-3.0.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:61631e08084be9e21a8967ec3139c7616ed7c5e9368e05c86d1b39562c8a57b6", size = 11658, upload-time = "2026-10-02T23:04:51.876Z" }, + { url = "https://files.pythonhosted.org/packages/a2/f0/d6613774d86fbf6d145751d43c59875e47a6f9f17daee0aef173bd36d90e/markupsafe-3.0.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0930db9bdc62d22944e10b066448bb65dc9abe9112880c7cab8da54db4284d5f", size = 12050, upload-time = "2026-10-02T23:04:52.931Z" }, + { url = "https://files.pythonhosted.org/packages/0d/f2/8f18e0b806eb13c1f8d07d917a720831ead54253a6dec011fbc78098a6f8/markupsafe-3.0.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6a45c3d514f2436064db00d7fc8778d888f0236ebfed649b53d13a59e69ad51b", size = 24363, upload-time = "2026-10-02T23:04:53.895Z" }, + { url = "https://files.pythonhosted.org/packages/60/ce/fa07dbe8a5675558fa36dea033e19995bc783de2dec5f540ccb9030b06aa/markupsafe-3.0.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1e1451fab512d1bcc3dc26988ec1edb0b82c2db909132872cd9356070a6b63df", size = 28525, upload-time = "2026-10-02T23:04:54.905Z" }, + { url = "https://files.pythonhosted.org/packages/85/40/be87c01f3868ec217f8a2015089d71c22c8c5a75324822e5ed1cdd87210d/markupsafe-3.0.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bd3ce56ae2cbae3ba82b683bc425cd7e48d2ed8b10f3e818186b6f5646d9271c", size = 24733, upload-time = "2026-10-02T23:04:56.229Z" }, + { url = "https://files.pythonhosted.org/packages/4f/a7/aeedb5140afa41fc74c225e9184ab96723a6e873b6ee1c9fede7283456d8/markupsafe-3.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8e124f974786f831d6043728e38296969d3579db8896fe004682f5758e613581", size = 22985, upload-time = "2026-10-02T23:04:57.521Z" }, + { url = "https://files.pythonhosted.org/packages/c3/fc/e91352bb08c6a59da3ef0909d457bf95a5f5908fbf151b30a06d9dbcfbb4/markupsafe-3.0.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c02e8f18bdedba082cef725942ac823b9b60656db07f7e265cb31618dfd00d77", size = 22001, upload-time = "2026-10-02T23:04:58.597Z" }, + { url = "https://files.pythonhosted.org/packages/5d/f8/bffee5e7d2a3deb59748a797650a48af7e672025cf641a79344a771ad106/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9f098115c247e11d138ab83a28fa0323c77015007ea2df73ba5fd714dfefd67c", size = 23793, upload-time = "2026-10-02T23:04:59.686Z" }, + { url = "https://files.pythonhosted.org/packages/ed/59/b853d6628ecb4d658e1d637224846d5e9bb4adf4f8df97f3be9f29dce2ec/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:d5f93ebbeb8032d47e349328ec8662d973d9b05a70b3c35df1f91fe419b84749", size = 22640, upload-time = "2026-10-02T23:05:00.768Z" }, + { url = "https://files.pythonhosted.org/packages/09/b2/1506df394f0f075797c418d0301498f49e43be194e3ffcb49e6fe6ccf022/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:64511c54db4e4987aef4c41923235927428729e8174c5dba488429be70a998ed", size = 24074, upload-time = "2026-10-02T23:05:01.813Z" }, + { url = "https://files.pythonhosted.org/packages/c7/81/5ed69cda630ac69ef60d06c09ba5a7f84ff66a2e28cf986fd5614ab3c6e6/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:e1a622f13970d81f95d0c72f9dc090dce9085fccfa4c9f2174377ee32bd15786", size = 21563, upload-time = "2026-10-02T23:05:03.239Z" }, + { url = "https://files.pythonhosted.org/packages/0c/fe/fb1e79be0fea60aa32602ebefc9c35a82bb42b4df157285ab7dfec12341a/markupsafe-3.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:c9a7f43c0b202b334cc9184af09bb8f21d3a209e038efaf106936fb69e6b026e", size = 23048, upload-time = "2026-10-02T23:05:04.479Z" }, + { url = "https://files.pythonhosted.org/packages/c8/52/7632a53360671a9b750cdbabaf9cdd89f18b42248b8e4cb42c0b0296e459/markupsafe-3.0.4-cp312-cp312-win32.whl", hash = "sha256:f0ec3b750b59375eab5b0fb2b9254810c00a3375be6d789899f1055a1d556237", size = 14108, upload-time = "2026-10-02T23:05:05.513Z" }, + { url = "https://files.pythonhosted.org/packages/3f/bf/62495e180b7000aaf30000fff849e933f74264638057176cf46852500adc/markupsafe-3.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:11935df9bf455ed0c04eb87bcd720f02b1fe5e02128a9430f23aed6f93336fc7", size = 14303, upload-time = "2026-10-02T23:05:06.538Z" }, + { url = "https://files.pythonhosted.org/packages/c5/8e/4c24208776a65878d656996945aacfbfe010d3720d1a98fc0eb8491fc03b/markupsafe-3.0.4-cp312-cp312-win_arm64.whl", hash = "sha256:a4bbd2d87dd233b9fc5812160c3d0ffbe42edc22a26ce0469f58479ede633fe9", size = 14174, upload-time = "2026-10-02T23:05:07.617Z" }, + { url = "https://files.pythonhosted.org/packages/6d/18/4bc5ba32499e87bb2b0ef5b3a9bb9c00a131fa961ddf0be548cb550f548b/markupsafe-3.0.4-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:de8b364c423ef0a4bad9069657d617f9a5d2b2062457a89b1fa16ee199c399c1", size = 12786, upload-time = "2026-10-02T23:05:08.709Z" }, + { url = "https://files.pythonhosted.org/packages/4e/6f/17f0c099bf25f3e31e63cc19244d9f6af861a9a4ab778c203997903cfdd0/markupsafe-3.0.4-cp313-cp313-android_24_x86_64.whl", hash = "sha256:34bdde374c5932765d7dc685c4a1d191a3207852d67e8e0a9eb6ea85156181f1", size = 12510, upload-time = "2026-10-02T23:05:09.93Z" }, + { url = "https://files.pythonhosted.org/packages/11/af/1a141081b905036ee904ec4bd945e1f70b4e1b32d33c4e59e8cf1d58b247/markupsafe-3.0.4-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:6bd9e1788e15bfcf6a9082de42e30387e7b85d211ab21e57a939bb8cfaaf8d96", size = 11583, upload-time = "2026-10-02T23:05:10.884Z" }, + { url = "https://files.pythonhosted.org/packages/e7/0a/a89385ae590232622a03e091805cff12f24fabe6c11e0e8bae096cece81c/markupsafe-3.0.4-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:5066b244f576f91afc8ee3ba029a89f99d39c79b1853fe9d39bea9f0afbec148", size = 11801, upload-time = "2026-10-02T23:05:11.913Z" }, + { url = "https://files.pythonhosted.org/packages/ed/85/ea548dc013962eb73653124bc595635fbf9e0fa41d1f181a967ccb784dfb/markupsafe-3.0.4-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:7a83aa6e4805df46fed18e989d3d16f86ef60cb50bbc8d9ce3a6be89165fbf6e", size = 11443, upload-time = "2026-10-02T23:05:12.887Z" }, + { url = "https://files.pythonhosted.org/packages/cc/72/15f2e5ec9cf2eb00d5cdfe968d94e4156a7bd7303832c3f3b2c403a36839/markupsafe-3.0.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2d1b7d9308288661f56672b1b157d75fc536714d3638487bbea17b6318a78248", size = 11665, upload-time = "2026-10-02T23:05:13.829Z" }, + { url = "https://files.pythonhosted.org/packages/ca/e0/4030bea613677e333c8a2c901fd405055f657f9d06acba5b7357984b6ef7/markupsafe-3.0.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:73e77980c7207854f00fc4e71fb1626868d5740ab4012623d55c7a99ad122a72", size = 12061, upload-time = "2026-10-02T23:05:14.807Z" }, + { url = "https://files.pythonhosted.org/packages/f3/a5/28b76a7449eb702966b88bef599e2360b411fbb3afeee8fe560939be06ec/markupsafe-3.0.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7018d4af1cd272e847aa5917983ab5e83e4f6579f9dbfecd4a79c0ca80b144c2", size = 24395, upload-time = "2026-10-02T23:05:15.909Z" }, + { url = "https://files.pythonhosted.org/packages/07/6c/21232811afc3a063b5e934b1ae2efda52f46154ec382f585149c020e61fe/markupsafe-3.0.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c90d5b3d4e944e065a301d741b3c1d784f6bd1f503aa68b4967e32b2ba313d85", size = 27183, upload-time = "2026-10-02T23:05:16.976Z" }, + { url = "https://files.pythonhosted.org/packages/14/38/6ccdfa5b59049cb36fb80cbc80aee9cf1fc9bb77d1335ad435f2070b08cf/markupsafe-3.0.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:18a801868a884f216e784d7d14db2a4077143ce7610440aee2ce8f734e7cfcde", size = 24772, upload-time = "2026-10-02T23:05:18.209Z" }, + { url = "https://files.pythonhosted.org/packages/63/e0/cec6865dfe88cb48fedd4b20aed6af5158e41092adcbf3e028bcc6ec2108/markupsafe-3.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:434139499bb20b502ed3baa1f169e618f924a97e7a777fea1a49446d80106cf6", size = 23017, upload-time = "2026-10-02T23:05:19.286Z" }, + { url = "https://files.pythonhosted.org/packages/ee/76/6ed4940bb7648a9aac457c14f870cfdd5105f139a0fb1f29cd61fafa47d1/markupsafe-3.0.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9e227f3dbe6bde7491cf0a9965d00b88c6b1a4a95d11480ddf88bb96d397c19f", size = 22036, upload-time = "2026-10-02T23:05:20.352Z" }, + { url = "https://files.pythonhosted.org/packages/a1/4f/ed476226d4fe46a09090a36025bf319296810028df55eb12f1253b540f3a/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:b8cd1f918b26fd7b1832ece557cc18f2d8747309ff8b3f0ef9d4250c5ad67a39", size = 23786, upload-time = "2026-10-02T23:05:21.576Z" }, + { url = "https://files.pythonhosted.org/packages/9a/35/66ff30450e35ef5fba9ebc930c9411747e537fd9447b65e44f5007e2b84d/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:a5fcffb37e602b0b3c1638a97746b9b96125caa9bcf6fa41d337a9261de231ee", size = 22672, upload-time = "2026-10-02T23:05:22.922Z" }, + { url = "https://files.pythonhosted.org/packages/32/0b/72f45ce4b4efcbca4b80cf1b06703eff0be8d37e82abb78f66c85a7ead1e/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5989cb26b2e1efc6a42216a9f6b5ee495ce5ace2e5b352a9af489976b32d1ee2", size = 24107, upload-time = "2026-10-02T23:05:24.175Z" }, + { url = "https://files.pythonhosted.org/packages/d2/03/71776e5fdcba04614b384cc102e8a4198208579d896fd1394cb7cb9aa900/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:add96447a86d205ab616665d53b2950ee81083757f56e6ea833c8b2917646b46", size = 21615, upload-time = "2026-10-02T23:05:25.215Z" }, + { url = "https://files.pythonhosted.org/packages/ab/5f/801ce02a02e7aee0f784b1ec7843026178f6adeb9c93ac67eb1992a9a84d/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:2628d3a8cb648ecebb3c5d6b0a1052d400e4d8b7ac0fb786be8d285b50040d17", size = 23076, upload-time = "2026-10-02T23:05:26.423Z" }, + { url = "https://files.pythonhosted.org/packages/4a/85/c43776625428f3bb4a61e8633940400e3efe6409e3c6f5bff26de5e45618/markupsafe-3.0.4-cp313-cp313-win32.whl", hash = "sha256:672d207103e6b16ca098611b0f9efad6bc00afd47c03d6ef62186495ca677dc0", size = 14118, upload-time = "2026-10-02T23:05:27.716Z" }, + { url = "https://files.pythonhosted.org/packages/6f/36/163da64de88a13db79214ef75fa041be7fa13bdb42261cf5b7484de14bfb/markupsafe-3.0.4-cp313-cp313-win_amd64.whl", hash = "sha256:1f1f9477e174582b0a1b583d60b66e1f2cf5d3fe12cee985e4aedf44766600e5", size = 14313, upload-time = "2026-10-02T23:05:28.749Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a8/9b662783ffaa1149221432a923cee562f78b9cbbb8baa3df9b3753e63e1e/markupsafe-3.0.4-cp313-cp313-win_arm64.whl", hash = "sha256:06de8ef6331f6e822c28d577dc8bf43fe398800477c49498f38fc38b67ff33fc", size = 14189, upload-time = "2026-10-02T23:05:29.917Z" }, + { url = "https://files.pythonhosted.org/packages/5c/c3/a944f3b0df22bd129e96915b9f4e98d2eeca6516687d7618304a966c3c74/markupsafe-3.0.4-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:4ed644d75aa94a2baf7ec3a96eaa160ea58c742eb9d27c6506053c5c40fc84ed", size = 12787, upload-time = "2026-10-02T23:05:30.971Z" }, + { url = "https://files.pythonhosted.org/packages/d4/d6/a44863f69d88b6c7e27889108f70d47aed259edf89d5df3c5fca1eac87d6/markupsafe-3.0.4-cp314-cp314-android_24_x86_64.whl", hash = "sha256:6d2a9efe686f9de00d0d1ea32a4a5a86d558a2277501bd78d964214eab625e59", size = 12525, upload-time = "2026-10-02T23:05:32.263Z" }, + { url = "https://files.pythonhosted.org/packages/17/8f/168ba80e532dd6a93f96f8f706f1ad41d7990b6e1aeedc1cc0d211a33497/markupsafe-3.0.4-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:8781a792a070cf2bd1b86d3aa943894115faaba6e88122a7bf32d62072742453", size = 11589, upload-time = "2026-10-02T23:05:33.251Z" }, + { url = "https://files.pythonhosted.org/packages/32/b3/aa2c95a574d3af39403a469b295886eb9b6d448da568cbebb5a2cbfdc2e5/markupsafe-3.0.4-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:971a3bbb75d97ae4e2e8f7d4834236f86f85f0c85e04ab2e191db1123b04f80b", size = 11801, upload-time = "2026-10-02T23:05:34.315Z" }, + { url = "https://files.pythonhosted.org/packages/60/d0/34b810107d83840e768bf485de795893ebbae35b26ab061b487adfa0a692/markupsafe-3.0.4-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:8909c2f1c6dd65e054ac4b573a91c8384d1492281e55d82d159d653f7a13adf6", size = 11447, upload-time = "2026-10-02T23:05:35.302Z" }, + { url = "https://files.pythonhosted.org/packages/6c/ab/2f8488f0f817a39fca068d2b17daf446bf5cdb3eae28c3720af534d873b4/markupsafe-3.0.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4cf3468d5ec187ffffcaca8e61929a37448f215dafc1386a12c750a72fe53634", size = 11722, upload-time = "2026-10-02T23:05:36.363Z" }, + { url = "https://files.pythonhosted.org/packages/ad/40/e2d117b048d47282ade906fbfd92814cbee5647afc13fda88a3406039372/markupsafe-3.0.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:52704c5d36eb6dda8866493decd61111fff86244c9b1ad225ca01b9e91e5970f", size = 12061, upload-time = "2026-10-02T23:05:37.397Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a8/73a81135e85ba66217f5af7facb03bbb386807e1a729ab64532e4c802652/markupsafe-3.0.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1caa2fa5a6184fb233153b35f654e6687bd555476f6170f29d8ee9be1a8b0af9", size = 24434, upload-time = "2026-10-02T23:05:38.407Z" }, + { url = "https://files.pythonhosted.org/packages/ac/ca/fa9216dd01efee2dfdacafe7df32b4d0170fbac694b0c258a193d6e53999/markupsafe-3.0.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:387d8cd30e69b3f0a72877b9ae717033396404e19095b17fe89753a981fda44f", size = 27183, upload-time = "2026-10-02T23:05:39.581Z" }, + { url = "https://files.pythonhosted.org/packages/fa/4e/a469509e538d37af51103b17b073126973f2b1cbf197ff32c7ddf025cfe5/markupsafe-3.0.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:051417f74bcaaefa316276e0ff723f541616ca51043d070da00249d9bddd3e3c", size = 24813, upload-time = "2026-10-02T23:05:40.671Z" }, + { url = "https://files.pythonhosted.org/packages/8f/db/d7282caf7ab03af44d5d6fdbaa019b35c7d7f1c90588b839c07cba640d6a/markupsafe-3.0.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a8e9f292fcda89b324f2f5c91d13f1424a153e40fc2756f38ee23b15835ff300", size = 23049, upload-time = "2026-10-02T23:05:41.864Z" }, + { url = "https://files.pythonhosted.org/packages/30/f3/b6a425206e6964efda6acee544d0eb01d1501784d0b8e2dcc74986f33b17/markupsafe-3.0.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:df1ae86ff54725a01fa1a0510b914ca53a161b7050be74f6204e24aded5971d0", size = 22088, upload-time = "2026-10-02T23:05:43.014Z" }, + { url = "https://files.pythonhosted.org/packages/ea/8a/84d3582fc1f0d5bd466cdf2eebf175e172158a6e70701aacec1de1b35430/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8965520ac587c94a4ac48b729be3d8b8de00af39699b17585dfb599babe77977", size = 23846, upload-time = "2026-10-02T23:05:44.098Z" }, + { url = "https://files.pythonhosted.org/packages/1c/65/db101cce51b7ba4864ac491a9859d297dd1adf0e55b103fee9db9c47c527/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:340cbb1957ba99929cbf19a75626d36ba1ae21d1730b287d1cf7f824a20c4fc7", size = 22674, upload-time = "2026-10-02T23:05:45.23Z" }, + { url = "https://files.pythonhosted.org/packages/e0/49/ddee9813d71db0c7a5c9d97c832125e6758a0c844777f1cf076569bb0e22/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:3a93d9616ddecfb393727a0041a562cf0b15a244e20f2bd25efc7949be4c4f17", size = 24104, upload-time = "2026-10-02T23:05:46.398Z" }, + { url = "https://files.pythonhosted.org/packages/aa/0e/7d8518d726726870a2399d69fd30d0fa36c5e57a2132c336b58d7c491073/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:d2e56fd3b00222722abfb3f5f0759ddbae4b90811b5ad4343c64030ad1bde70c", size = 21637, upload-time = "2026-10-02T23:05:47.48Z" }, + { url = "https://files.pythonhosted.org/packages/b4/b0/b505e8a361ba557dbf3b3aa7331ea39b00d2022a26e925ff8463b9714bb3/markupsafe-3.0.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0d9c47709875fdb321452056622e930c52afbc07a7d780762fbb8b4d91ce6fa4", size = 23081, upload-time = "2026-10-02T23:05:48.611Z" }, + { url = "https://files.pythonhosted.org/packages/1c/ea/9cc3cea873f980c75cbdb6f4277ce30ee955de38be0b3d02f14c108e0698/markupsafe-3.0.4-cp314-cp314-win32.whl", hash = "sha256:38fc55594dab834470b6733dead2ee9e3f657fb0608c769dcafa0ba5ab52f45c", size = 14272, upload-time = "2026-10-02T23:05:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/80/f0/5792ff768a410f93ee3f84fc19345295ffc352d2c936b424cb37e514714c/markupsafe-3.0.4-cp314-cp314-win_amd64.whl", hash = "sha256:c1bc67752d5f21013cfe430df4062441714eab79f65a6a05e01505957e9c35fe", size = 14501, upload-time = "2026-10-02T23:05:50.788Z" }, + { url = "https://files.pythonhosted.org/packages/5f/cf/3d074a8edffcc6899355232ff2543ae8d929733239596423b7db79698bc9/markupsafe-3.0.4-cp314-cp314-win_arm64.whl", hash = "sha256:7e1636da3d8dfc220b6dd10264db5f2b165e4888c4518594898fbe381049af8a", size = 14364, upload-time = "2026-10-02T23:05:51.857Z" }, + { url = "https://files.pythonhosted.org/packages/d9/31/87ce42159aae2163cf3bbbd0c44bc87780510eecab1ea3859099aed95dcb/markupsafe-3.0.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:805c8b84534fa10891890f0e4be39f3a99e94615d93e8836bf9fa1fdca2feeb2", size = 11759, upload-time = "2026-10-02T23:05:52.951Z" }, + { url = "https://files.pythonhosted.org/packages/5f/53/b047207eeb7752e960aca3eb1df5fb7eefa7dd4c62ac49bb156456c8a702/markupsafe-3.0.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:fa95848c929b6a75f6848d3c9793e59db365ee436776e57db835cdbfa79ba977", size = 12096, upload-time = "2026-10-02T23:05:54.066Z" }, + { url = "https://files.pythonhosted.org/packages/ee/51/4326c88a13c7b755657d44b4bb986f8c3d9843ecba7e22d98661d87f9a57/markupsafe-3.0.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e916035e3e9930cbdfdd10abf48861340221857f45509565898e012263f7b289", size = 25699, upload-time = "2026-10-02T23:05:55.15Z" }, + { url = "https://files.pythonhosted.org/packages/f2/bb/990581b7474bfcf2cf34bed6ba5ea23bd87adb9d671213d68e88620e7a6b/markupsafe-3.0.4-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b4d12837e0203bbace818ff4a7461afdcd78bcd782351cea148139180d7bcffe", size = 27804, upload-time = "2026-10-02T23:05:56.29Z" }, + { url = "https://files.pythonhosted.org/packages/6b/89/89491878c28e8291f5aa2fffe2c2d57230d10ae366d55dd810b840513d78/markupsafe-3.0.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5086f9975abb1ab531ee6afca1761e4b59a19b446f3f6522ed776963228cfe5a", size = 25912, upload-time = "2026-10-02T23:05:57.416Z" }, + { url = "https://files.pythonhosted.org/packages/30/77/680998b54efdea06fc114565cd739b6d059f826a0279219b218dfa750d29/markupsafe-3.0.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b4a635a0487774f841cb1fb62e907e7195cc95bc761e053184b8acc3ceb20733", size = 23623, upload-time = "2026-10-02T23:05:58.557Z" }, + { url = "https://files.pythonhosted.org/packages/ae/75/2709f5ac5de9467b40b10e2bb8f89cc63dfb74582e09aa734b1124a217de/markupsafe-3.0.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cb96e6e088d6cf71c1ea977510948320234824cf226e32f6f6e044f7a9c82b34", size = 23301, upload-time = "2026-10-02T23:05:59.94Z" }, + { url = "https://files.pythonhosted.org/packages/a0/c8/39eadc6c5b14c9c7679bfb98f4d4c6a97863b5beb91839aca4d2d6e16e55/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8b5d563170ff8ba3181caa967c99a3c804d1dedb702c7cb93a6a7c32247da978", size = 24950, upload-time = "2026-10-02T23:06:01.289Z" }, + { url = "https://files.pythonhosted.org/packages/1a/5e/01037f8a43e8ccb0bffb4fbdc5212db05bf080fdd7286cd392332d58128a/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:396ec4e65cc889f69786b3b89478b471cee5a3bcf468b9d9bb03e1a30fb291fc", size = 23330, upload-time = "2026-10-02T23:06:02.441Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f4/23e83ce0596bb0cbe670502d31df8f757bbd01a392aa486fa3b40d1ed399/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:15ba9e28640feef770374b116a6f019c21f52404aeabe516aa7f800587b98cfc", size = 25239, upload-time = "2026-10-02T23:06:03.579Z" }, + { url = "https://files.pythonhosted.org/packages/88/5b/3708897368073cc683d524750474f41a77d2986152c380dcc55b20fdf340/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:d920abdfa61279ba1a2ef9484aab07bf03331f8c08a10120fa332353d06e6932", size = 22767, upload-time = "2026-10-02T23:06:04.699Z" }, + { url = "https://files.pythonhosted.org/packages/c6/61/ebda1307864b409e6b3115757a3d4a09cca46cfb6cc65191b5de226b424b/markupsafe-3.0.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:a9f54054101545a9a9cccefddf54316aa6e4491611fcbef9e91b3b6bebec04f6", size = 23668, upload-time = "2026-10-02T23:06:05.9Z" }, + { url = "https://files.pythonhosted.org/packages/09/15/98075cceac3b5ba0dbb8e4762a847be967d2befc349a2cf2d0ac77f62c9d/markupsafe-3.0.4-cp314-cp314t-win32.whl", hash = "sha256:12a606a492de952afcb43b59a14aaaaad120e708d3663dd0fdf2d738d427a691", size = 14301, upload-time = "2026-10-02T23:06:07.109Z" }, + { url = "https://files.pythonhosted.org/packages/0b/a3/768b560fcc4156685cb563d922b217810cfa7bc135773367f62f1f9d2078/markupsafe-3.0.4-cp314-cp314t-win_amd64.whl", hash = "sha256:a18f38cafc329bac5e3c2b96c765b4c96d3d103421ed22ab7988c1e3fce27464", size = 14526, upload-time = "2026-10-02T23:06:08.276Z" }, + { url = "https://files.pythonhosted.org/packages/93/63/da554b4c97a6b0ea3229ca7fe8cbfb620be81613d517f482e85958550537/markupsafe-3.0.4-cp314-cp314t-win_arm64.whl", hash = "sha256:eba154571c16e032112afac0dc2dfe9e63c2ceb7aedd07bb7eecf2ce26d4dd4c", size = 14421, upload-time = "2026-10-02T23:06:09.402Z" }, + { url = "https://files.pythonhosted.org/packages/a9/30/54d11c8ca027114898cab97421fb39e4ffd9ddf47cdbc44df2ec76722da9/markupsafe-3.0.4-cp315-cp315-android_24_arm64_v8a.whl", hash = "sha256:737c9c3981998eba27f11786f84fddcbabc74068b72a4a1f454ea02094b57b65", size = 12791, upload-time = "2026-10-02T23:06:10.485Z" }, + { url = "https://files.pythonhosted.org/packages/10/6d/97c913e253a14bd3cd0e15a5c56d13203b823fa7ee32498342896a072dc4/markupsafe-3.0.4-cp315-cp315-android_24_x86_64.whl", hash = "sha256:489505b03f692c3f376394e49194fa7a7f9e8558d6e293a7056a0032b0c38163", size = 12527, upload-time = "2026-10-02T23:06:11.834Z" }, + { url = "https://files.pythonhosted.org/packages/26/f9/b86d032042a4d597d9e1997f0e5f63a3eedaf11258e0a05760b0a0a826ea/markupsafe-3.0.4-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:077293e425f28ec737dbcad442a71752e28f8ae27cde3d68acd1fb212091cd92", size = 11602, upload-time = "2026-10-02T23:06:13.122Z" }, + { url = "https://files.pythonhosted.org/packages/f2/dc/73c14c1eedf0ac5fa3292ba43435e6c49d2c2050f33cebde541f8f4807f1/markupsafe-3.0.4-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:9348cbb300d224fe3b89793262cb093504d4ae927004468463f745188a193e4a", size = 11817, upload-time = "2026-10-02T23:06:14.227Z" }, + { url = "https://files.pythonhosted.org/packages/8f/69/2c2fcaa5fcee22d72c7819c0d536fd181c74a688e6143845419579cd2863/markupsafe-3.0.4-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:b807e598953730f82e4eae3bd30f6a122cf6b31c398c6b504c0e04c13c170429", size = 11446, upload-time = "2026-10-02T23:06:15.574Z" }, + { url = "https://files.pythonhosted.org/packages/88/54/9e5ec76c62e6e2834d5a93623018c943e8b3bb41d663e3fd4c03303b9b85/markupsafe-3.0.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:799c39bdf5e2f1292fedd3009f7b3c9e760f10b2420cb9638d56920840ff6db8", size = 11719, upload-time = "2026-10-02T23:06:16.701Z" }, + { url = "https://files.pythonhosted.org/packages/96/24/3ec292b44064c16229e064d770b2625bd8ea941aa61f44905a9fa44942c0/markupsafe-3.0.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:ae9dcb8fbe244cb82f8a6458b455b927a03685e383d9bacf1ea5ce180b96dc97", size = 12075, upload-time = "2026-10-02T23:06:17.855Z" }, + { url = "https://files.pythonhosted.org/packages/aa/85/b64fdb1f304848518742136983c24e96d967bfb59a0ea160e92736901ab0/markupsafe-3.0.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4bced6e2a6dba6a28f7dd3c6ce14df1b2dd495923f16ea484cad03decd463b2b", size = 24656, upload-time = "2026-10-02T23:06:18.963Z" }, + { url = "https://files.pythonhosted.org/packages/9c/18/23997d4c65b355da6390d61cd56e0ab3befd6ba8dda25cb40c602bd0fa6b/markupsafe-3.0.4-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3882fb412298575bae3b9c46868251f15cc69307359f87bb1b382e53d6e5a2c9", size = 27737, upload-time = "2026-10-02T23:06:20.117Z" }, + { url = "https://files.pythonhosted.org/packages/d4/36/35998dead3c6af88c38265a56e58100211f036234ab88eb2283fd4cbce44/markupsafe-3.0.4-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:04e7902ba80ee4bac1d50a549606527a1dcf0476cd81403db41099d3b60ec653", size = 25003, upload-time = "2026-10-02T23:06:21.284Z" }, + { url = "https://files.pythonhosted.org/packages/82/96/ef49135ce260db4ca4a12b119ed468449cd248db6b1468e2112b546d7a2e/markupsafe-3.0.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:925f929d6b59a8b3f8b8c6ac363cd0af7eecc81efb3071770b3c6717c450a369", size = 23111, upload-time = "2026-10-02T23:06:22.524Z" }, + { url = "https://files.pythonhosted.org/packages/50/7d/83126e338bd88c17a220668235368ad719fd4638e426739858cbb8508f77/markupsafe-3.0.4-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f68edfc67aabac33708941f26f22a7b8e9f81429bc0cf249fcf7d66b23af8d19", size = 22403, upload-time = "2026-10-02T23:06:23.785Z" }, + { url = "https://files.pythonhosted.org/packages/83/dd/daf7e420de23c8206c365204e7b85e1251d8e19d34196a56336f316e5ed2/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:e5c802729725bd07e2bc3ab7b76dc7e0bbfc53129d8f1eb1c002c24cf774717e", size = 24083, upload-time = "2026-10-02T23:06:25.037Z" }, + { url = "https://files.pythonhosted.org/packages/19/3c/11eecdc06bc44ad5570350085b572ebf049e8f9a38d1ece6d76640b739cd/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:55ffd6ce583d97dc71dc92e930324c8c0d25aea7e3ade6ae54ef77cedb096811", size = 22931, upload-time = "2026-10-02T23:06:26.328Z" }, + { url = "https://files.pythonhosted.org/packages/0d/9e/ac0fd77f2a726e56ecc3ca0235d095feace1358d1b822406c2a2ef26a4dc/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:2cb3dd71fc6be918ad4264346a8ed69485f9b7ed7bf35495d8e22807cd6b8bea", size = 24299, upload-time = "2026-10-02T23:06:27.742Z" }, + { url = "https://files.pythonhosted.org/packages/d7/09/c6bd842ad58ff5b3bc76eeed7e9a42a6f11adc5d090ec697b72c9672731e/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:94f5407f7bc64fa6463906b896f9904beeeb7dd8dc116ee8e9056c8714ff9916", size = 21948, upload-time = "2026-10-02T23:06:29.274Z" }, + { url = "https://files.pythonhosted.org/packages/a3/46/82f586711fed61e86faa1ee1bc317d68cd45a10c8bdbe3f7d1fdf9026ad8/markupsafe-3.0.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:2dad610540cb2e6272855c178f08ae9a1c7ac258a7fb71660553a5f104b42741", size = 23150, upload-time = "2026-10-02T23:06:30.583Z" }, + { url = "https://files.pythonhosted.org/packages/19/2d/2dfdce99318abbfa26925195fbc17db188c46a1ec6457be121b6f9cfeb42/markupsafe-3.0.4-cp315-cp315-win32.whl", hash = "sha256:03470d1a8268e692ecf79ecd565593e59d44219377a7ead61f1f1b94c1f7ff6b", size = 14269, upload-time = "2026-10-02T23:06:31.949Z" }, + { url = "https://files.pythonhosted.org/packages/5b/ec/6000fd82e8791e58fcd0456ec20f098957e2b03d5ed02eb73241a577c0ba/markupsafe-3.0.4-cp315-cp315-win_amd64.whl", hash = "sha256:d882a373d8093c2941e01291b7ced96e9cbe4781da9a7751ca7e6c70385e5214", size = 14496, upload-time = "2026-10-02T23:06:33.258Z" }, + { url = "https://files.pythonhosted.org/packages/bc/66/e73bd5016421d5d6e2fb6de7dd609f9de020942ac8c626526bd8c6eeaf82/markupsafe-3.0.4-cp315-cp315-win_arm64.whl", hash = "sha256:353bd63081912ab8cfa6a0c7d185934cdf8426f04c618bba6bc4b394f2069b67", size = 14361, upload-time = "2026-10-02T23:06:34.539Z" }, + { url = "https://files.pythonhosted.org/packages/90/df/cb8c3dc98d313a951df2f8968f44e4cb5643df6d3cab749a530ce2f7d972/markupsafe-3.0.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c61750fadcd119d0825bcb7d7d675dd264dcc89cc05292aab5be68ebdbb374ad", size = 11760, upload-time = "2026-10-02T23:06:35.807Z" }, + { url = "https://files.pythonhosted.org/packages/d6/bb/4af9b3ca0753d654ac75f9531d5bd741bb77ca6e696f36807c475ffc099a/markupsafe-3.0.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1c0df495a977d10460a94941799c72d5b5ab03d3858d949b55b5a66c8f371c99", size = 12108, upload-time = "2026-10-02T23:06:37.089Z" }, + { url = "https://files.pythonhosted.org/packages/3f/d4/b56429313aee5fd59b079c3df5615299959e25e7113eb6d8caadbdd7d38a/markupsafe-3.0.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:02fa4acbc6a3fc5c693c34d4dd8c1130b7fe99cc915181b0ddd6f72aeb296002", size = 25762, upload-time = "2026-10-02T23:06:38.419Z" }, + { url = "https://files.pythonhosted.org/packages/65/f5/34c181e891aa4f7d59c918584672e0c5eb7fffe76c1387d1246008bf4081/markupsafe-3.0.4-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:05295589e619b9bed252a86b532b8e27350abc372d18ba89b59375325e91ec1e", size = 28400, upload-time = "2026-10-02T23:06:39.819Z" }, + { url = "https://files.pythonhosted.org/packages/ce/b5/ad14694fd0ac9a5ce30bc6498f2999378f418583dd1679cca5a1b512957e/markupsafe-3.0.4-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:be6cb0c799abb0e2ba3e618e6d28ddddf7e485f6c2ce938dfa237daf3905072c", size = 25946, upload-time = "2026-10-02T23:06:41.381Z" }, + { url = "https://files.pythonhosted.org/packages/d6/a8/26b606445387d0ceb1eb1f21840094b84e4e3c3c3983d80d10b89823b490/markupsafe-3.0.4-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:26e9867520db70d37f7fb421a7f0d8adb40171011fb84ce869afa1a83370dfa8", size = 23634, upload-time = "2026-10-02T23:06:42.748Z" }, + { url = "https://files.pythonhosted.org/packages/39/a2/b8814de672f1f0094d498bf646f2fec9d6356b503d28ef500b71c5095377/markupsafe-3.0.4-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f03460ff076f70ab595bb45a0205ccea1971443575b6920c52e755dec2b3fbfe", size = 23488, upload-time = "2026-10-02T23:06:44.176Z" }, + { url = "https://files.pythonhosted.org/packages/db/c7/287223376fb73335a3cc5d6eb22c6ab01358cf33945a9c39c06b9dac3f4b/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:436e3ffc6310d3c41878c601db29098102fe5d8a467c49da4a4125254e0980f2", size = 25037, upload-time = "2026-10-02T23:06:45.646Z" }, + { url = "https://files.pythonhosted.org/packages/f9/29/4df8355e313426d19e62ba33e0253c009ca12a0894ee77d67fa67255361c/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:4e2c4809c14559aa7ef426f27fb35afbb38104c349a903bf8f3600456764bb38", size = 23543, upload-time = "2026-10-02T23:06:47.264Z" }, + { url = "https://files.pythonhosted.org/packages/71/e5/8377731e8495668dcc768f645e717df18318c841edaf023a99395f6da9b4/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:da2af0d7aebfc2074080d72efa6ab8317c62481ef1f896f65d9999c1c01f4494", size = 25282, upload-time = "2026-10-02T23:06:48.795Z" }, + { url = "https://files.pythonhosted.org/packages/ed/5f/373456e37ceb1478d657d6fe769cbe0a39f0a8dfc1548eeb19c471eefdd9/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:aa2c838cc024642cc04c6854232f32b43e5e22833dd11119c1766c7873b8370d", size = 22993, upload-time = "2026-10-02T23:06:50.31Z" }, + { url = "https://files.pythonhosted.org/packages/d7/93/2cbd5628435afb6f541bbaced4bce0c2edac4b09a142e6e928b8b0da9858/markupsafe-3.0.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:b91cc9d336957239ff200f30097e6fea2dc6d6fb3c81e853eaa09eac904fd894", size = 23712, upload-time = "2026-10-02T23:06:51.759Z" }, + { url = "https://files.pythonhosted.org/packages/81/99/157e10966b033b363aeda5263e82596ee232a0b1d082fdbf90aa417ff083/markupsafe-3.0.4-cp315-cp315t-win32.whl", hash = "sha256:e49fb0d1ce92cfa0cb198cc5b1b11cdf9d0638658e2a2db2687e39db7c87fc78", size = 14300, upload-time = "2026-10-02T23:06:53.241Z" }, + { url = "https://files.pythonhosted.org/packages/33/05/55884815414c9706a23deca150b72c25a62109e65b0b6ce232077802c719/markupsafe-3.0.4-cp315-cp315t-win_amd64.whl", hash = "sha256:4f6e0852a0283b1b1fd776eeb7b766a5f440b3e2bd31ab51af3b400585f3965c", size = 14522, upload-time = "2026-10-02T23:06:54.729Z" }, + { url = "https://files.pythonhosted.org/packages/92/f9/ecbde7149e95b8a0f18e16d5d747f7dc06049d5da2e4f77f6f5e4a1f46a8/markupsafe-3.0.4-cp315-cp315t-win_arm64.whl", hash = "sha256:39dbacefc411633db5b4378b066a9aca70a3d7e2922c9e578d825f844026eeba", size = 14417, upload-time = "2026-10-02T23:06:56.246Z" }, +] + +[[package]] +name = "mergedeep" +version = "1.3.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3a/41/580bb4006e3ed0361b8151a01d324fb03f420815446c7def45d02f74c270/mergedeep-1.3.4.tar.gz", hash = "sha256:0096d52e9dad9939c3d975a774666af186eda617e6ca84df4c94dec30004f2a8", size = 4661, upload-time = "2021-02-05T18:55:30.623Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/19/04f9b178c2d8a15b076c8b5140708fa6ffc5601fb6f1e975537072df5b2a/mergedeep-1.3.4-py3-none-any.whl", hash = "sha256:70775750742b25c0d8f36c55aed03d24c3384d17c951b3175d898bd778ef0307", size = 6354, upload-time = "2021-02-05T18:55:29.583Z" }, +] + +[[package]] +name = "mkdocs" +version = "1.6.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "ghp-import" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mergedeep" }, + { name = "mkdocs-get-deps" }, + { name = "packaging" }, + { name = "pathspec" }, + { name = "pyyaml" }, + { name = "pyyaml-env-tag" }, + { name = "watchdog" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bc/c6/bbd4f061bd16b378247f12953ffcb04786a618ce5e904b8c5a01a0309061/mkdocs-1.6.1.tar.gz", hash = "sha256:7b432f01d928c084353ab39c57282f29f92136665bdd6abf7c1ec8d822ef86f2", size = 3889159, upload-time = "2024-08-30T12:24:06.899Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/5b/dbc6a8cddc9cfa9c4971d59fb12bb8d42e161b7e7f8cc89e49137c5b279c/mkdocs-1.6.1-py3-none-any.whl", hash = "sha256:db91759624d1647f3f34aa0c3f327dd2601beae39a366d6e064c03468d35c20e", size = 3864451, upload-time = "2024-08-30T12:24:05.054Z" }, +] + +[[package]] +name = "mkdocs-autorefs" +version = "1.4.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e0/e0/1e8ed4e8dabdcba8cba5dbf4b8ce49bb3b51e750177155247abb5345d48a/mkdocs_autorefs-1.4.5.tar.gz", hash = "sha256:856f75b327b7717923ce06267094650689a510a748c48657f5333965950c2788", size = 59736, upload-time = "2026-10-22T15:03:55.402Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/cf/3dfc07ec910553bfb1e5c9009c1854bd9d2efa7f3dda03f007a77db0e63a/mkdocs_autorefs-1.4.5-py3-none-any.whl", hash = "sha256:68ee484e0800f3ba50cda1bc4a94293adbdfcc010243c322b3f5d66e15d06770", size = 29633, upload-time = "2026-10-22T15:03:54.091Z" }, +] + +[[package]] +name = "mkdocs-get-deps" +version = "0.2.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mergedeep" }, + { name = "platformdirs" }, + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ce/25/b3cccb187655b9393572bde9b09261d267c3bf2f2cdabe347673be5976a6/mkdocs_get_deps-0.2.2.tar.gz", hash = "sha256:8ee8d5f316cdbbb2834bc1df6e69c08fe769a83e040060de26d3c19fad3599a1", size = 11047, upload-time = "2026-03-10T02:46:33.632Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/29/744136411e785c4b0b744d5413e56555265939ab3a104c6a4b719dad33fd/mkdocs_get_deps-0.2.2-py3-none-any.whl", hash = "sha256:e7878cbeac04860b8b5e0ca31d3abad3df9411a75a32cde82f8e44b6c16ff650", size = 9555, upload-time = "2026-03-10T02:46:32.256Z" }, +] + +[[package]] +name = "mkdocs-material" +version = "9.7.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "babel" }, + { name = "backrefs" }, + { name = "colorama" }, + { name = "jinja2" }, + { name = "markdown" }, + { name = "mkdocs" }, + { name = "mkdocs-material-extensions" }, + { name = "paginate" }, + { name = "pygments" }, + { name = "pymdown-extensions" }, + { name = "requests" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/cd/c05d3a530ba7934f144fb45f7203cd236adc25c7bdcc34673d202f4b0278/mkdocs_material-9.7.7.tar.gz", hash = "sha256:c0649c065b1b0512d60aad8c10f947f8e455284475239b364b610f2deb4d0855", size = 4097923, upload-time = "2026-07-17T16:21:33.156Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/21/17c1bc9e6f47c972ad66fb2ac2568f99f90f1207eeb6fc3b34d094dba7b5/mkdocs_material-9.7.7-py3-none-any.whl", hash = "sha256:8ea9bb1737a5b524a5f9dcf2e1b4ebda8274ae3008aa7845720a97083bef708f", size = 9305438, upload-time = "2026-07-17T16:21:30.017Z" }, +] + +[[package]] +name = "mkdocs-material-extensions" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/79/9b/9b4c96d6593b2a541e1cb8b34899a6d021d208bb357042823d4d2cabdbe7/mkdocs_material_extensions-1.3.1.tar.gz", hash = "sha256:10c9511cea88f568257f960358a467d12b970e1f7b2c0e5fb2bb48cab1928443", size = 11847, upload-time = "2023-11-22T19:09:45.208Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/54/662a4743aa81d9582ee9339d4ffa3c8fd40a4965e033d77b9da9774d3960/mkdocs_material_extensions-1.3.1-py3-none-any.whl", hash = "sha256:adff8b62700b25cb77b53358dad940f3ef973dd6db797907c49e3c2ef3ab4e31", size = 8728, upload-time = "2023-11-22T19:09:43.465Z" }, +] + +[[package]] +name = "mkdocstrings" +version = "1.0.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jinja2" }, + { name = "markdown" }, + { name = "markupsafe" }, + { name = "mkdocs" }, + { name = "mkdocs-autorefs" }, + { name = "pymdown-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/53/71/f85bdf13355073ae15a7375f09879375a830553552e58c1c4b7e0bbc5c8b/mkdocstrings-1.0.6.tar.gz", hash = "sha256:a0b8c2bdd29a6416c80d717aa369bbf7831946bd9f23c2a66db1b1dbe7693dbd", size = 100649, upload-time = "2026-07-11T19:38:05.732Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/5b/4c1902e8bdd5c4db63284e9d101dece4038d4025d6d88850ffe0a1578980/mkdocstrings-1.0.6-py3-none-any.whl", hash = "sha256:2703708697487d1b6d6d7b412e176fa436edf120c1bf81dc9e126b12d00893c7", size = 35787, upload-time = "2026-07-11T19:38:04.417Z" }, +] + +[[package]] +name = "mkdocstrings-python" +version = "2.0.8" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "griffelib" }, + { name = "mkdocs-autorefs" }, + { name = "mkdocstrings" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c5/65/0db919b7c91bf033b42d04f15ff16a56f4edd6afb26e84d448359660ece3/mkdocstrings_python-2.0.8.tar.gz", hash = "sha256:34545b54681cf0b212aab95394d37b0f5326a93b102f6ad1df3d965c79384c9d", size = 201771, upload-time = "2026-08-31T20:16:06.698Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/b7/a5a854d4e44853f26decc0c5e0d68df052399f3da344a313da4178f00816/mkdocstrings_python-2.0.8-py3-none-any.whl", hash = "sha256:e555d9ef53b0febdeae4dd603144d4f86ec90fef672276645ea3bb61232c3d24", size = 105443, upload-time = "2026-08-31T20:16:05.25Z" }, +] + [[package]] name = "obstore" version = "0.12.1" @@ -183,6 +685,33 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, ] +[[package]] +name = "paginate" +version = "0.5.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/46/68dde5b6bc00c1296ec6466ab27dddede6aec9af1b99090e1107091b3b84/paginate-0.5.7.tar.gz", hash = "sha256:22bd083ab41e1a8b4f3690544afb2c60c25e5c9a63a30fa2f483f6c60c8e5945", size = 19252, upload-time = "2024-08-25T14:17:24.139Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/96/04b8e52da071d28f5e21a805b19cb9390aa17a47462ac87f5e2696b9566d/paginate-0.5.7-py2.py3-none-any.whl", hash = "sha256:b885e2af73abcf01d9559fd5216b57ef722f8c42affbb63942377668e35c7591", size = 13746, upload-time = "2024-08-25T14:17:22.55Z" }, +] + +[[package]] +name = "pathspec" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/82/42f767fc1c1143d6fd36efb827202a2d997a375e160a71eb2888a925aac1/pathspec-1.1.1.tar.gz", hash = "sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a", size = 135180, upload-time = "2026-04-27T01:46:08.907Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.14.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/96/549558270586699a271a18b1111482dc3fc39baa0ef61d183e230d2c961d/platformdirs-4.14.9.tar.gz", hash = "sha256:c6b188e03ffd4dfe1bf8c4bcb47cd94711af244a9852dbff60297bd753684d5d", size = 87729, upload-time = "2026-11-27T20:53:44.721Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3b/e7/fc53dfd2f9469cce9be9c58385bdcdb5087e790c135c9dadd4cc8401bb3d/platformdirs-4.14.9-py3-none-any.whl", hash = "sha256:d0d3a23e7ff282cfa94b77f5a22b81030dcb68ba0430f90c74f4bd8d090782ea", size = 94272, upload-time = "2026-11-27T20:53:43.511Z" }, +] + [[package]] name = "pluggy" version = "1.7.0" @@ -201,6 +730,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, ] +[[package]] +name = "pymdown-extensions" +version = "11.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markdown" }, + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/21/a9/5f0c535ba3b08fe09270c16808e053a968868242ecbd5676d4e3a488bf28/pymdown_extensions-11.0.1.tar.gz", hash = "sha256:dd2905ae6fc5b75582fafb139a1266ffc754705efa902aa50067fa7ff4f94ec0", size = 857113, upload-time = "2026-07-02T17:59:22.955Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d6/54/da572c98c0b77626a91b5d3b89f0231d8bff5125c225420908632f8b342d/pymdown_extensions-11.0.1-py3-none-any.whl", hash = "sha256:db3943a62bab7e03af1364f0c4083e64b91fb097675a4b6cceccfbe9a77e5eb2", size = 269455, upload-time = "2026-07-02T17:59:21.271Z" }, +] + [[package]] name = "pytest" version = "9.2.0" @@ -217,6 +759,143 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" }, ] +[[package]] +name = "python-dateutil" +version = "4.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/39/b3927f3616f6223832f9b760e4208e8a7c7e1dea2b4d9ad7d32a5d214c3a/python_dateutil-4.0.0.tar.gz", hash = "sha256:d7295ff14fdc0f92f662100bfb6c551d160ca090f2939f1ec5b9794265c03f06", size = 250419, upload-time = "2026-11-01T07:02:42.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/76/b8/c0b780928e2fb1c87e9e375818c6f121da2398b071012d1747be300b83f4/pyyaml-6.0.4.tar.gz", hash = "sha256:e24bf71af8a432d7808fabff134d38dfe16d3cbb41f2873bb4b1e42422de0a1a", size = 136336, upload-time = "2026-11-20T23:37:05.977Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e1/ba/fb2aad330bc4f31041f989630ceae5f32e307d3ba9819573d35b71e078fa/pyyaml-6.0.4-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:180ac792c958c2173f6e4467c55ae5f73ab1a9a624ee29fc7095c56d5e3a4055", size = 190856, upload-time = "2026-11-20T23:34:50.753Z" }, + { url = "https://files.pythonhosted.org/packages/16/da/1b8397614250ec63bb7ef1cbb0aa5878367ff729ef35a4abf2accbf48a18/pyyaml-6.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:730788375056c43d3ac15bd894c9cd2fb7a931a38b302f408620c64b3ef176ed", size = 180950, upload-time = "2026-11-20T23:34:51.629Z" }, + { url = "https://files.pythonhosted.org/packages/fa/88/d99fc8f2cfb33ab7786fb3f6da90eddc1ed9709196bffcb4a487d7f53844/pyyaml-6.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71bb5b87465d88d1dfc577115af6d435bff9b26f2512936f610c26aa55966028", size = 810905, upload-time = "2026-11-20T23:34:52.77Z" }, + { url = "https://files.pythonhosted.org/packages/d7/7f/500e5ec119990d1784c72b64197cee8a4f2982f6bc76c572af7f8df02385/pyyaml-6.0.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b9fe0b8c65a1611053eb7fcaa7c022f655b7eebeb0ea034572615453cae6b843", size = 914779, upload-time = "2026-11-20T23:34:54.086Z" }, + { url = "https://files.pythonhosted.org/packages/9d/3e/c1c307b6c03e4ea7d86f166f14920ead07aecc35e88d873814d12aa2da66/pyyaml-6.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:622aa875fa6533f25fedcffe23079357d65a690d462200afed5d8e9d0e01ebee", size = 828016, upload-time = "2026-11-20T23:34:55.213Z" }, + { url = "https://files.pythonhosted.org/packages/03/49/dc931722d7de757596c1c3b944287e4f7d3f419655cd8f5fae382c6179e6/pyyaml-6.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:49e38a95e24738908ea852e61df0abc58d1e4d4f974ccdb2386eaee412bedc67", size = 799807, upload-time = "2026-11-20T23:34:56.589Z" }, + { url = "https://files.pythonhosted.org/packages/bf/8b/2b7ad9af1c6c5b147c3c860a31586737034a83693d7ae86f854036c6aeb4/pyyaml-6.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4d3bbc5e8a84a5a6775adecac786f489510a7159b1c343d6f31426d888cfdd6e", size = 836213, upload-time = "2026-11-20T23:34:57.655Z" }, + { url = "https://files.pythonhosted.org/packages/8c/d8/ebdc04bbf7c00a3c78ea577322239534556418a958d2242af8c0c6ef9093/pyyaml-6.0.4-cp311-cp311-win32.whl", hash = "sha256:c0d68d972f6f6417b4e85e9522f3d57bb4fbc924379766ccd87254a31009c1cd", size = 146012, upload-time = "2026-11-20T23:34:58.75Z" }, + { url = "https://files.pythonhosted.org/packages/7f/c6/ffe94f3159f3543b1ea1702519e1e0a74a67f3a255c286c1f00d51780b82/pyyaml-6.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:0db75f402e99c25239003a499c214a61947b4ef5312af34711d4c63e5c179318", size = 161819, upload-time = "2026-11-20T23:34:59.853Z" }, + { url = "https://files.pythonhosted.org/packages/86/df/5aec8a8c65e4c11fab31b55d53029d8013e5ccfcf409c20f8175e3e267c7/pyyaml-6.0.4-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:1088ad740f50c13178dad16fbc2fa1f634c791d42c7009fdb390e38e5b90b788", size = 187835, upload-time = "2026-11-20T23:35:00.829Z" }, + { url = "https://files.pythonhosted.org/packages/c7/30/efaabf2d135d11f32cbd4752f3b7df0d592894ee3ca252bbba013a7d5891/pyyaml-6.0.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4d30c2f186612bd2f9f07c08a4c96721af59cfc8da3ec7cb27dfa2834e8bb019", size = 179510, upload-time = "2026-11-20T23:35:01.826Z" }, + { url = "https://files.pythonhosted.org/packages/af/fb/d5ff6957db5c843151ff13196277bb8e20b2d5db2e2db3e8d051038d888b/pyyaml-6.0.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45e37dd647db9d67b757444c74060c064ace5fdaa08f42bf4fda3812275d423e", size = 814700, upload-time = "2026-11-20T23:35:02.923Z" }, + { url = "https://files.pythonhosted.org/packages/c4/de/569b907a281bbc49b934bcdad881486b7a476b011cf733f936ca85a8b37d/pyyaml-6.0.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9e7ec9dc75cadd392fd687cc9b8ccf7dd59ada0a991e0d14ae0fad9ecdba00c3", size = 879806, upload-time = "2026-11-20T23:35:04.34Z" }, + { url = "https://files.pythonhosted.org/packages/94/80/1d27f7084b983b7cfd1fb35e65a38276d9eddfdcdabc0922bb26cf9521bc/pyyaml-6.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:93bfb2459195406a518e2f487a9bbf01df240175f31e06f5a252ac6734c7bbf0", size = 849249, upload-time = "2026-11-20T23:35:05.457Z" }, + { url = "https://files.pythonhosted.org/packages/53/37/9b49dff68570bedf27a05ff447e9a281d75bbdfa4d08dc1ee100a844c612/pyyaml-6.0.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:84e97378010f3da8daf673b82d39ed638098d236a1b760d61c0c1348a642bd70", size = 799796, upload-time = "2026-11-20T23:35:06.566Z" }, + { url = "https://files.pythonhosted.org/packages/05/bb/f7df529541b98113bea84129a78f93c3889acb08385ca25f9786823dce67/pyyaml-6.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f5c410f9e2ffc9286279a46f2e8c107edaf3b1123510af59c828a9c15b23c9db", size = 825424, upload-time = "2026-11-20T23:35:07.783Z" }, + { url = "https://files.pythonhosted.org/packages/44/00/fc5d40087cc55bf3d7bb5ef55cc3e6513e6946afe33a188680fe1d846eb0/pyyaml-6.0.4-cp312-cp312-win32.whl", hash = "sha256:60e9da2772e259307650e03c24f50e3bc2d9fa5ed1ba44c47582e13b0e7708d1", size = 140667, upload-time = "2026-11-20T23:35:08.846Z" }, + { url = "https://files.pythonhosted.org/packages/a3/95/307a6ceafbad9a08300743d19329c31726224e583e05c4fe5358522ba283/pyyaml-6.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:131d11bd9b60d705a6388366d77ed67850995a4d2be85fe149785a257c17e531", size = 154452, upload-time = "2026-11-20T23:35:09.792Z" }, + { url = "https://files.pythonhosted.org/packages/62/81/15c300b14cca818cb9ee27d8cb61cc124229d04f4f7f7bc4e3fca8e2e8d8/pyyaml-6.0.4-cp312-cp312-win_arm64.whl", hash = "sha256:69380d4bae12aab2a2c9532deff6a2841bc9fda47c333691bd2368b696301768", size = 147167, upload-time = "2026-11-20T23:35:10.763Z" }, + { url = "https://files.pythonhosted.org/packages/95/22/b445c43210fe7f466fcf5a38bcbe850fd3db31b85594db22b5a43e63c482/pyyaml-6.0.4-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:61eef2f08e977b725f37a8d1663f5a222c6f09207ac0794030d5fca062e7c96e", size = 188392, upload-time = "2026-11-20T23:35:11.776Z" }, + { url = "https://files.pythonhosted.org/packages/1f/c3/1536ad41fd962d3915f3f8252ecc7f91192ab15c3120ba72ff45e76b7077/pyyaml-6.0.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9d4211f080920629a90c9e31c51e326fb70cfae38f18d4128b9913c23642bace", size = 179961, upload-time = "2026-11-20T23:35:12.722Z" }, + { url = "https://files.pythonhosted.org/packages/40/fd/c5297cc6370e4ab63d0c44d2e63510cc53354f5e8e74bcff047e2a384698/pyyaml-6.0.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:41b4669c3a8fd5750e594dff59d3e62d40e321fec467b50449603710ed0a68f3", size = 804464, upload-time = "2026-11-20T23:35:14.066Z" }, + { url = "https://files.pythonhosted.org/packages/0c/2e/20385f63727a6c08df1adad34a88bde90e2bcc1146d1c8588a83190d53b8/pyyaml-6.0.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:efe68ed09903cca9ab4117c2b9ea6ee8d369818808945bb5a7fa8009b5630b45", size = 875357, upload-time = "2026-11-20T23:35:15.537Z" }, + { url = "https://files.pythonhosted.org/packages/70/f2/f280d52f22f6d9853517d02495c02fbf4c80214fae8ca498efa8605013da/pyyaml-6.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50588147ab2c6a59b5f990a4905db80899a6c2bd197e046a6201f1e67587e794", size = 838459, upload-time = "2026-11-20T23:35:16.681Z" }, + { url = "https://files.pythonhosted.org/packages/2a/ee/5f7142110583686e94ab4492e3724ed0869cd9fe26ba8293ec25a47ee223/pyyaml-6.0.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4d1e8d6e345b4b4424a05a11e699e999e65a88f422f73636f8a0b354bf219ffa", size = 789384, upload-time = "2026-11-20T23:35:17.734Z" }, + { url = "https://files.pythonhosted.org/packages/4f/ab/1fd22df5305561cbefb85363182a0af5e81d219e8b8b8dfd73f20eb70859/pyyaml-6.0.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a56491babf0d976625807953bd192dd9de973fccb3270e77b1a795b152a26175", size = 814502, upload-time = "2026-11-20T23:35:19.171Z" }, + { url = "https://files.pythonhosted.org/packages/c1/5a/6b53e1711a78fcc14619a341618c36b862ad8c634e7bc43ae18e6a7376b2/pyyaml-6.0.4-cp313-cp313-win32.whl", hash = "sha256:1631d566655f3af7d6c4a4485267830f6b680d3dc9704b659b3c3f4541b5a3fe", size = 140447, upload-time = "2026-11-20T23:35:20.134Z" }, + { url = "https://files.pythonhosted.org/packages/bd/09/e785d2a9d64de2449cc3aecaa03f1c34670d7a688dc00da7246a858b7e8f/pyyaml-6.0.4-cp313-cp313-win_amd64.whl", hash = "sha256:0a3a351f04dc124f9357512bdb80ac37cd1750cf1371da33e7cbb96d80ac865f", size = 154298, upload-time = "2026-11-20T23:36:22.105Z" }, + { url = "https://files.pythonhosted.org/packages/94/44/0ed649c2c1cc37b342042c3a4609247b74201c23a6f7f01f5dd222eae2bd/pyyaml-6.0.4-cp313-cp313-win_arm64.whl", hash = "sha256:f617e4e5c619fef5284335b24e3af3a77ce08dc5c389ff4b25033bb2749032b7", size = 146938, upload-time = "2026-11-20T23:36:23.305Z" }, + { url = "https://files.pythonhosted.org/packages/70/90/a2d37db959cb771389bb6171eff83905776e5aead12a985a5118a587d6eb/pyyaml-6.0.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4a329472db6c8858ebd94f2214a54c8bff8f035a6cc7af1ab39cc1b33a5f0e56", size = 189727, upload-time = "2026-11-20T23:36:24.518Z" }, + { url = "https://files.pythonhosted.org/packages/71/40/de4380acb2bcc733f502a7c8562b08f741890741dcaa8a7f018c87acc060/pyyaml-6.0.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:7335809813ec838d9cd334b1744cda33deb141c9ef23a9c0df371c37980d3851", size = 181969, upload-time = "2026-11-20T23:36:25.675Z" }, + { url = "https://files.pythonhosted.org/packages/7f/a1/88baf9d84981ea723fc1dd5cb534548caebff3071939f899509ab7c62d2f/pyyaml-6.0.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ed9b957abb12f6ffcd92d5db32fa3ffd4e4a8423d80ddd51b4efa63b42f6a76b", size = 804091, upload-time = "2026-11-20T23:36:26.979Z" }, + { url = "https://files.pythonhosted.org/packages/b8/d4/ce94fe5b0e3cc04834d4a30237c1b5388a13ff5a383b919e857898834857/pyyaml-6.0.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b525488d5addf5d59ff4610cd8b1deab9dc97fe0fb3fb74533d7f65e9792bd92", size = 869794, upload-time = "2026-11-20T23:36:28.069Z" }, + { url = "https://files.pythonhosted.org/packages/ef/1b/54ce11b40c8fa1883f14eef46525c3c329509dcc268164074fbe60add8ed/pyyaml-6.0.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c604dc2613c417130479cdd6e55c2faa691b6365aa82b3dafddfcecc2eaf1ac7", size = 819491, upload-time = "2026-11-20T23:36:29.189Z" }, + { url = "https://files.pythonhosted.org/packages/8a/d2/6202ffb5d61667c993211a9231836b5d9be5e34165efd1714ac68ea76029/pyyaml-6.0.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:f1a4a85b419f5cb6470dd4be5f766bc59532f11b9c22c076b58a0348f05dca5f", size = 790345, upload-time = "2026-11-20T23:36:30.597Z" }, + { url = "https://files.pythonhosted.org/packages/d4/39/d62587fae4a9a32197ea43182c38f221f3f173a09c6f4380254533bdd89e/pyyaml-6.0.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:132c3c7c37a8e6f334921b05cfea5d26e241d792dcbb4db0462129d25ca53b43", size = 824626, upload-time = "2026-11-20T23:36:31.9Z" }, + { url = "https://files.pythonhosted.org/packages/b4/b5/e5cf6ca786f8a5b9bd91e01fe8f2113300bc5628fcfdd3ca02d271970824/pyyaml-6.0.4-cp314-cp314-win_amd64.whl", hash = "sha256:1d2f08c122727c86f8303bb1dd45159ca1de1f2d68798e671ec46974e321008e", size = 157525, upload-time = "2026-11-20T23:36:44.254Z" }, + { url = "https://files.pythonhosted.org/packages/75/9c/d78ce9adda3f7db933f73bb2b17ede76f5786fff747a2b73f6e8a6b7bab5/pyyaml-6.0.4-cp314-cp314-win_arm64.whl", hash = "sha256:33506a2620f0e7c49858f09cb44e99f144878d03af3d9c10aa136e9a1d103bcd", size = 151175, upload-time = "2026-11-20T23:36:45.191Z" }, + { url = "https://files.pythonhosted.org/packages/83/f0/e48b8e9736380a039a17506200c4c3080ef181ee86b0e8e2cd6c345ae78a/pyyaml-6.0.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:1db4d51d3c2c9545dd44c614febc4594240754f74b30d8e501415b118347f0d1", size = 193903, upload-time = "2026-11-20T23:36:33.086Z" }, + { url = "https://files.pythonhosted.org/packages/98/ba/682030d1e08f2e4bbd57f164b9085d37560386cf54f6299825e754b32d1a/pyyaml-6.0.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:93da48af92c84c4236578e330a514ca324362c0bb62894d8d2343363ed57ff03", size = 188971, upload-time = "2026-11-20T23:36:34.034Z" }, + { url = "https://files.pythonhosted.org/packages/e9/2b/4b29107aae981b4d4575945a73d6c73ebd407d27934dcf35a7daa8fbeb43/pyyaml-6.0.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3c7129bcee5c88c1450802cc6a95b690ee7c51bfcc7a9b60bbd9549a7a4fcbe6", size = 851356, upload-time = "2026-11-20T23:36:35.21Z" }, + { url = "https://files.pythonhosted.org/packages/12/d4/2b05dddc8f59c3762e67c8d5ac01c1759767ee6ea4aba183a01950644668/pyyaml-6.0.4-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2018fda285d1289527a389e1b4ace1e2d3af410930f949136b55ecb0747744d1", size = 887294, upload-time = "2026-11-20T23:36:36.484Z" }, + { url = "https://files.pythonhosted.org/packages/3e/2a/ce3e0ff674c67b9e1706912aae61063581b3dba22142e60ccdaa64b25c75/pyyaml-6.0.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:15c52bb238a15bb4fd7e6342a5ac71d594507667c7fe0e5a5abbc0f6875d1e91", size = 850982, upload-time = "2026-11-20T23:36:38.247Z" }, + { url = "https://files.pythonhosted.org/packages/7e/ad/701d83221865b2512067a9ab2b8e062145af2d362cc2451e72c146ef34cf/pyyaml-6.0.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ab874ebcc5c12c31c859a9e9fe159d688df1f7a099818ef8a35906264a8f5d6b", size = 822547, upload-time = "2026-11-20T23:36:39.852Z" }, + { url = "https://files.pythonhosted.org/packages/61/d1/d88b389313be382ddabd1bca86dbf5da31ac02ecbf29c893588aafb6e11f/pyyaml-6.0.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:62c5b5669b05dabf991a705f3a3601f57b65e95121a1d3e3a4ae4446c8632865", size = 845538, upload-time = "2026-11-20T23:36:41.285Z" }, + { url = "https://files.pythonhosted.org/packages/1a/a6/c25ff1b5ebc8bfb11a783a5fde40435f0459629af6f56f9487479bca9766/pyyaml-6.0.4-cp314-cp314t-win_amd64.whl", hash = "sha256:609e8efaffa5662da16b7d53eef76fc4eedbbe56fce5829b67ba808a6e35d399", size = 164060, upload-time = "2026-11-20T23:36:42.238Z" }, + { url = "https://files.pythonhosted.org/packages/08/ad/25d2ac566f0e2f4eb822c9c5e8d9a053406cbfff142273a072b194856823/pyyaml-6.0.4-cp314-cp314t-win_arm64.whl", hash = "sha256:a266cf55ee5cf63c1803432a61c6386e750e0012ca49d12d26ccb0ffd80b343a", size = 157379, upload-time = "2026-11-20T23:36:43.181Z" }, + { url = "https://files.pythonhosted.org/packages/e5/29/fb680bd299c2c6e004c1cc1914f8bad276c6014fe8debd5d6d61ea4c4ff4/pyyaml-6.0.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:12a155bc41509d71a2eb73e2191d9e400c1345ea99ac3d9946c31f40a4c840f8", size = 189560, upload-time = "2026-11-20T23:36:46.145Z" }, + { url = "https://files.pythonhosted.org/packages/af/6c/2ffdab56d7afeb039d957479a305516ddbaa08d0162d1e9165fb928e3aeb/pyyaml-6.0.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:070c22b6f490d6cc30912be9fb9ab1af9c752769b39b53616f6510c3f038ee6a", size = 181949, upload-time = "2026-11-20T23:36:47.065Z" }, + { url = "https://files.pythonhosted.org/packages/b3/07/3a20ed31a60084206ac20449583b0d1a42116b3c530d6857918e4ddbe4b6/pyyaml-6.0.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:872d2a592289061c1b987e335b3568a2616b474be02bd0608d8f551a385441cd", size = 803806, upload-time = "2026-11-20T23:36:48.145Z" }, + { url = "https://files.pythonhosted.org/packages/26/5b/3dd56027457b96e7e5ea2f4f5976e530d699884b4fd4e360e99e57fa6cca/pyyaml-6.0.4-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:914b19e17814315fbcca52031bf79b68237f3d87a948c584a667b18b468e4df7", size = 876808, upload-time = "2026-11-20T23:36:49.294Z" }, + { url = "https://files.pythonhosted.org/packages/b0/51/096a5495b33ff2da32f0c84f5bf8e042cf76f72641cba06ee9618ad01f4d/pyyaml-6.0.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c57e40928738c4a202852759f9e1ee2c7063429a9469ee1ac15651bbf7d69963", size = 833052, upload-time = "2026-11-20T23:36:50.505Z" }, + { url = "https://files.pythonhosted.org/packages/da/75/b4e86b5a27fcb9a9cf88e3b81d1b0c12cae2734311e508af18b93ff56286/pyyaml-6.0.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:8e0cd755ce5e9009fd95f9c553e5942478feb8f7dffa19435641fcdc3c20e8ca", size = 788983, upload-time = "2026-11-20T23:36:51.821Z" }, + { url = "https://files.pythonhosted.org/packages/2c/00/2a2cdad68237bcd416bd01688ecfb0e3fa1e68a841b74193db97ffd1c716/pyyaml-6.0.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:2c11be5ab4d9f603a598b5ce93a2064ae38087bdf1b384c5397170054cda4e36", size = 828806, upload-time = "2026-11-20T23:36:52.959Z" }, + { url = "https://files.pythonhosted.org/packages/a8/15/39efefc88dd6fbc3be23cef08a819f5e8bf9a6c0bcf003fc09d38dd0010e/pyyaml-6.0.4-cp315-cp315-win_amd64.whl", hash = "sha256:67da066ca12eb60114ea87f2ecbcca622fff0c205c743cc900437127564fabf6", size = 157467, upload-time = "2026-11-20T23:37:04.171Z" }, + { url = "https://files.pythonhosted.org/packages/40/1d/fddc53420d9c12e7d27c36a59fabf186ba1f6117314da4927dc40b2da19b/pyyaml-6.0.4-cp315-cp315-win_arm64.whl", hash = "sha256:573debb9fe3075423d4f823795a678580e597218c25baef178d532b124a25a25", size = 151203, upload-time = "2026-11-20T23:37:05.079Z" }, + { url = "https://files.pythonhosted.org/packages/fa/ea/48e62a25084fc4b317f8bcc5c9823ddaaa73a0c7769ca451dda6919ff491/pyyaml-6.0.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c680622f85979f2ff59b4ae44c1ecb5566b2f0f0ffe5d0dc8b4bb6a0e916dabb", size = 193500, upload-time = "2026-11-20T23:36:54.416Z" }, + { url = "https://files.pythonhosted.org/packages/49/dd/8c4df6becc936125261607073fbcd55e1d902a8d53ae4e4893d53b9df0ef/pyyaml-6.0.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:18ea9bda247857fc0de05181675dc116b54c1b04ca3db71de5d2108c882823b7", size = 188474, upload-time = "2026-11-20T23:36:55.651Z" }, + { url = "https://files.pythonhosted.org/packages/d0/63/b60236ef09cbab7c5ce174aff59d49a3425b9a8e9bbe4690bd3b9b7d4fba/pyyaml-6.0.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6ac167ebebc0c387290406a337b9b5c8c343fa5f7928d5941e45a94b8ba3aa39", size = 848311, upload-time = "2026-11-20T23:36:56.961Z" }, + { url = "https://files.pythonhosted.org/packages/f6/3b/4b14f064ae5d6f69638a86bb7bf1a46d02bb4de083798e693a4a83b1418a/pyyaml-6.0.4-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4a2a8f27d24d4cdc05aa11df5f4c08e13f30d9e6674809b6a5ddcfcba49a653a", size = 891181, upload-time = "2026-11-20T23:36:58.077Z" }, + { url = "https://files.pythonhosted.org/packages/01/36/4e0b01e380bf3695d34a4bf6b9272c529f4c8d3195c733687d64fb9f8f06/pyyaml-6.0.4-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e956541cc7a3fff2bb5b17aeb6c5bb42c86c8e6dafb5ebdd41a05e72e702076b", size = 855715, upload-time = "2026-11-20T23:36:59.165Z" }, + { url = "https://files.pythonhosted.org/packages/6d/a8/2784a29e687fa7a5882d47c925a98d1dbdd60ead521be14a9342c6a74ff9/pyyaml-6.0.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:8708f6ab9c2581ffa05f66dae3206bb0385949650537d7295fc7ab0d6454dd70", size = 818754, upload-time = "2026-11-20T23:37:00.248Z" }, + { url = "https://files.pythonhosted.org/packages/bb/85/62d54e223b4bc89ff85f087a5ce2648e5d929d3214d64613dbae17d5e045/pyyaml-6.0.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:a65339c24f2fb8d4419e06ceec1bda98bdcff727b3b533a81d5af6bb2dd34520", size = 845763, upload-time = "2026-11-20T23:37:01.331Z" }, + { url = "https://files.pythonhosted.org/packages/eb/40/6bd9090368664be984a83fd7fe64f8e044b067a52449679c309706e3199d/pyyaml-6.0.4-cp315-cp315t-win_amd64.whl", hash = "sha256:a3cc63af3d639d1609143711837b926183418260aae89ed95193c07b25b99d33", size = 163170, upload-time = "2026-11-20T23:37:02.3Z" }, + { url = "https://files.pythonhosted.org/packages/0d/22/468d36762a0c650cf2295052998eb1d419053335ea9ff48a043f5ae4d578/pyyaml-6.0.4-cp315-cp315t-win_arm64.whl", hash = "sha256:d276f23e2371deb5ee68dd252cc9c2402b806b54d8d2cc7efbb6c34c3a78d886", size = 156942, upload-time = "2026-11-20T23:37:03.209Z" }, +] + +[[package]] +name = "pyyaml-env-tag" +version = "1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/eb/2e/79c822141bfd05a853236b504869ebc6b70159afc570e1d5a20641782eaa/pyyaml_env_tag-1.1.tar.gz", hash = "sha256:2eb38b75a2d21ee0475d6d97ec19c63287a7e140231e4214969d0eac923cd7ff", size = 5737, upload-time = "2025-05-13T15:24:01.64Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/11/432f32f8097b03e3cd5fe57e88efb685d964e2e5178a48ed61e841f7fdce/pyyaml_env_tag-1.1-py3-none-any.whl", hash = "sha256:17109e1a528561e32f026364712fee1264bc2ea6715120891174ed1b980d2e04", size = 4722, upload-time = "2025-05-13T15:23:59.629Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "ruff" +version = "0.16.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/78/449cb84790bd5cc3823b2652ee405a4558856e5c4195aee3a16bf7b3eb5d/ruff-0.16.8.tar.gz", hash = "sha256:9247bf92b5f04d825c8639a4fe423ec2e4222acd9222e58412b0dab7e442798b", size = 4938814, upload-time = "2026-09-16T15:54:46.688Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ac/25/6071aabc530e9be7e2c195e8fe3f7aea2735405b6cf447212832d7811831/ruff-0.16.8-py3-none-linux_armv6l.whl", hash = "sha256:6ffbd6d87383c1edf5f6fa890f10200950240d7c1a16052a19a09d3a2307dd38", size = 10048966, upload-time = "2026-09-16T15:53:57.605Z" }, + { url = "https://files.pythonhosted.org/packages/54/98/07f90ecbc74dd5fb5764f11f2bc774d6a7cffef92d2ff5f5b4e9e23c754e/ruff-0.16.8-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:42ed6b878ed61e3acca92f2730a17acff39286944ea82398544696366a6f925e", size = 10165498, upload-time = "2026-09-16T15:54:01.14Z" }, + { url = "https://files.pythonhosted.org/packages/fe/1f/e6a712e3b47cad4a40600134105ed193cb773f618a42eb7ba323cb812cc0/ruff-0.16.8-py3-none-macosx_11_0_arm64.whl", hash = "sha256:7ea781c7f2afba8c6a505ea0fb3f994020249e0c450635f5381286fea6b46170", size = 9830004, upload-time = "2026-09-16T15:54:03.998Z" }, + { url = "https://files.pythonhosted.org/packages/23/f2/311a08776d75d81c7676e20b6b020ae63cbe881fcdc7a8dd64e6e18bdd93/ruff-0.16.8-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8efeae3bbe414a5efefda11a792dfb51ef90ac48d50c4830de2f644caf3e8659", size = 9986558, upload-time = "2026-09-16T15:54:06.804Z" }, + { url = "https://files.pythonhosted.org/packages/f3/ed/37b6cb3d3ba8c73e68ae3eb1d502383beb5aa05a582bb7bb3a922f929f54/ruff-0.16.8-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3a79b795469fef7fc6e908b218eed2eb17332afd85031db6480dc864560e69b2", size = 9877332, upload-time = "2026-09-16T15:54:09.552Z" }, + { url = "https://files.pythonhosted.org/packages/22/cc/40873a8f36ad084cc540d55fcca7077264d5b13b24659e9180c176fb2b08/ruff-0.16.8-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3fdc5563cdc50555e6fba39322850860e9267c1b3d12c26a74729d8604c3c812", size = 10507125, upload-time = "2026-09-16T15:54:12.152Z" }, + { url = "https://files.pythonhosted.org/packages/c3/e4/fc91a642b78ccbab6b9477720f3644ae7a10a9bcce69a934679cd64f62bc/ruff-0.16.8-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:34508983c70665578dab88f5223d8e6228307e1135398ca8bfc8b7e9501e282b", size = 11336694, upload-time = "2026-09-16T15:54:15.489Z" }, + { url = "https://files.pythonhosted.org/packages/c2/3d/bbd2a9a600a4e73dc3e7548a249c8d1671273464b55822c6fae50f602dff/ruff-0.16.8-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:644bb578569e0ffc575741232bd385dacdd6fbe123f1a729e7a225f54aa3957f", size = 10774448, upload-time = "2026-09-16T15:54:18.16Z" }, + { url = "https://files.pythonhosted.org/packages/1a/41/d83af9879a7b6e8bf5fe16b1da0b134049d2f5d3afac12defb0897cb84bd/ruff-0.16.8-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:15e7d226246961db9235098333caa13063906d3851136b84c2900b82f5daa1df", size = 10323796, upload-time = "2026-09-16T15:54:20.743Z" }, + { url = "https://files.pythonhosted.org/packages/f5/2c/cefd07bfe914b84943ea769ade8d607bd22750b965d3228eefd7cebd15d0/ruff-0.16.8-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:a2bf6bc3e9ebdd4449abc6f06cf64b98051a2c61cf94d2fe9596518c881f1a1e", size = 10514115, upload-time = "2026-09-16T15:54:23.497Z" }, + { url = "https://files.pythonhosted.org/packages/f3/9d/76a2e26c79a23be6e6e3664c57bec9e9fc8de155cfb9e4b67ea91b64f9d7/ruff-0.16.8-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:6ca111ba0849539165e9e59d2b442542f3c1e8060ebbdea82494f1ffbccb1e1f", size = 10072582, upload-time = "2026-09-16T15:54:26.185Z" }, + { url = "https://files.pythonhosted.org/packages/2e/d4/f42edddb39668af1a559ceafa3823aedd65633a48dc9768e775485faa2c1/ruff-0.16.8-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:359a1e5b495448ee1e91018064382ebc86f90e8aac2fed222c7d0e4e8df85fd2", size = 9879644, upload-time = "2026-09-16T15:54:29.278Z" }, + { url = "https://files.pythonhosted.org/packages/f8/d4/913e3195d95e0378786c6656945c865f534a3560e29139da4882aff630d1/ruff-0.16.8-py3-none-musllinux_1_2_i686.whl", hash = "sha256:59e8f5681349474110b24d62e93cfda6593f5fa3473446ca3705200cac1a08b9", size = 10231569, upload-time = "2026-09-16T15:54:32.036Z" }, + { url = "https://files.pythonhosted.org/packages/2b/c4/8aa6ea0bdcedbd1bf87397e2fc4ed8406448ea5842f8660bc6e5f163039d/ruff-0.16.8-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:efa3e7a16d1baaa79957888dfdf8be9ef2e44db81cb032af06d76632ab59e773", size = 10663666, upload-time = "2026-09-16T15:54:34.838Z" }, + { url = "https://files.pythonhosted.org/packages/3d/02/7f10ef4700bc223c30a3fdd10631a29830c45524b810a3c7ed947af64591/ruff-0.16.8-py3-none-win32.whl", hash = "sha256:55793ba85c69921e89be061426d91a78652d6e50317c962240922747a4eb713f", size = 10093472, upload-time = "2026-09-16T15:54:37.47Z" }, + { url = "https://files.pythonhosted.org/packages/1e/5d/a509c07d714b6da88f2c518b4637cf6f1d46b074be8f0f1e5fb9ff5126fe/ruff-0.16.8-py3-none-win_amd64.whl", hash = "sha256:a6b85621fd3c81e31fc5f5add09c9c078b430db3595ca632efafdec9e64ebfaa", size = 10586899, upload-time = "2026-09-16T15:54:40.488Z" }, + { url = "https://files.pythonhosted.org/packages/fe/a0/50787329e4f20bf9dc9f6230015d46ec69c51a97ace5bc202dae4755365d/ruff-0.16.8-py3-none-win_arm64.whl", hash = "sha256:d075e820af612102ce217f07cc93e69f9490b10ec13ea85fa87bd03d996cef8a", size = 10386316, upload-time = "2026-09-16T15:54:43.332Z" }, +] + [[package]] name = "sortedcontainers" version = "2.4.0" @@ -235,6 +914,75 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, ] +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +] + +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + +[[package]] +name = "watchdog" +version = "7.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/d3/38e18c9559b96fca53df98979e72cafcd498aba41b57f0830fc31008ffc2/watchdog-7.1.1.tar.gz", hash = "sha256:d7dc3bf0c3417c002ee976e958479c54d8ca18cbb3532fadbe69511fa389da15", size = 256722, upload-time = "2026-11-21T13:21:10.133Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/b8/41eb6d8c431c8f54417700c932961d0cb49b7113c39a1496cbabb81d29c3/watchdog-7.1.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:0c7c72fc3cd4c9fe1e9bd356b4c22ba999a95f32d0199b41b22b53b17d2ecdc8", size = 133054, upload-time = "2026-11-21T13:20:24.046Z" }, + { url = "https://files.pythonhosted.org/packages/59/33/ae4e7eb4d73de73aaa5c9c00ad621be7eb574cfedfb1ab8559f24e0877c3/watchdog-7.1.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:09c29980d0469b0fe25a3de78f7314e56b224ccdc9c97ab736508b3ceb8a6327", size = 125494, upload-time = "2026-11-21T13:20:25.258Z" }, + { url = "https://files.pythonhosted.org/packages/d4/b1/ada93de58092873d7e59fd2cc07811eaf3f7edf412f11df9e41ecd2ce788/watchdog-7.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:0c3d34267f0c4a9397c3891d3d40a0c75e7dcb5889266788e99bd3c878e8eedd", size = 126011, upload-time = "2026-11-21T13:20:26.222Z" }, + { url = "https://files.pythonhosted.org/packages/3d/93/9777c97dff5a4326451b19c7b381980da053306cd7c4b26560800c714eb6/watchdog-7.1.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:a1ca497559d1fb32eae26f10c1fb2aca82042fed4441bcbaebbd7f585f09ef0b", size = 133123, upload-time = "2026-11-21T13:20:27.31Z" }, + { url = "https://files.pythonhosted.org/packages/95/85/260a4343c05965cfd21e208c1e7fa2a4dfb1b78b17cdb3fdbad87ed829c8/watchdog-7.1.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0a37521b6088d81df2f4d94dc2cb10b23fe873c68f6fadadd36dd9bf83dde736", size = 125510, upload-time = "2026-11-21T13:20:28.601Z" }, + { url = "https://files.pythonhosted.org/packages/56/52/d304d39d7192b9957cb3d4ce4bf1ae24628db8d81b6d7cf0777b92134956/watchdog-7.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a785b40ecb69f7743762663aaf0d8303b9a0ea6372710f38fe390a912507fc46", size = 126064, upload-time = "2026-11-21T13:20:29.663Z" }, + { url = "https://files.pythonhosted.org/packages/ea/61/c33f2282e2eae5895d61b932ab31dc7c8110cd677dac438830a0e3587c3c/watchdog-7.1.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8b25decbd54c270e3f7f23ffbccfdd485346c95cc4845116d98f5c5cf159be15", size = 132951, upload-time = "2026-11-21T13:20:30.658Z" }, + { url = "https://files.pythonhosted.org/packages/01/7f/340d2caf18065568c41339da96317ba5403a5dbc632d7a8b7b3a688ca2af/watchdog-7.1.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:aae3d997730089bdf30ae724122cda4617f58a40603d63a3495ce48d2b50ba0c", size = 125425, upload-time = "2026-11-21T13:20:31.59Z" }, + { url = "https://files.pythonhosted.org/packages/6a/e9/006a7815ce4c652301adf0d309864df94eebfcbf4b74570ac17987450af2/watchdog-7.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:536064ddeb3671534181004a45867d1abc32566f45054910772c4eb7e14d945d", size = 125981, upload-time = "2026-11-21T13:20:32.943Z" }, + { url = "https://files.pythonhosted.org/packages/cf/bb/72606973f77f66d7a3271fd5785555f7c27d3690ab99d798a51a3e1d2f3a/watchdog-7.1.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:05e85c22dcd53f7152d1e03e785e241341d586b06a5115be7c0ea86436ccc1f6", size = 134588, upload-time = "2026-11-21T13:20:34.578Z" }, + { url = "https://files.pythonhosted.org/packages/3f/71/e99c3e40cb86d985271bbd42db58eceb4a3dedfb27ddf4dad8e52e5caabc/watchdog-7.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:7c7838dc644664f750a25b1a273a9c0cee7978a0adc903915dc13ff74225e9e4", size = 125564, upload-time = "2026-11-21T13:20:35.568Z" }, + { url = "https://files.pythonhosted.org/packages/09/af/636074f1cf35e00645bcafb9fd07ce53b13a436a456e34ba8b1bb3e51622/watchdog-7.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:30f127042a876812f117a17e7fa52f66958a157e3deffef87fbd0001bcd90bb9", size = 125990, upload-time = "2026-11-21T13:20:36.512Z" }, + { url = "https://files.pythonhosted.org/packages/a6/35/9a31a334e2c924951cd729765ca85703a744dec3a18ad4103e04f4153ade/watchdog-7.1.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:896e9d00a11c0af24e138fc82511d5bb1e4465c0caa4bec442598e060d5afdaf", size = 135203, upload-time = "2026-11-21T13:20:37.672Z" }, + { url = "https://files.pythonhosted.org/packages/3f/21/96b6d51db3be2fe70f45a7f6ed943278af3eafac557cb35410e44b13d45e/watchdog-7.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:d1e1bac43768d0e413256a058d4e28024489cf4a9ef9835a2ba29b936887ebc8", size = 125833, upload-time = "2026-11-21T13:20:38.572Z" }, + { url = "https://files.pythonhosted.org/packages/a3/3b/e9498be66e7cc662afe8f489cdf4490265d2b35c2d471799377bfa1c8869/watchdog-7.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7d4eabe2b5612b1434c7da3db517f6df38cc3ea50fd7907d571ec44bfadbb305", size = 126330, upload-time = "2026-11-21T13:20:39.448Z" }, + { url = "https://files.pythonhosted.org/packages/78/88/23d4820805b76dd80df16c30490331088a5b0953c982349db4fe8e2a2114/watchdog-7.1.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:d55b9572480f8a0d3f644a854639f97e578cdf6ec8af0ecc3aef2336e252657f", size = 134638, upload-time = "2026-11-21T13:20:40.395Z" }, + { url = "https://files.pythonhosted.org/packages/5b/b5/edc85c208bb0d3a5b664801b2cbc49cecda2fd7ba44c26cf009357d3b0ec/watchdog-7.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:7c5bcc506e648465338dcef4134c7db0f90eda65610658c63d26224008869a9d", size = 125563, upload-time = "2026-11-21T13:20:41.388Z" }, + { url = "https://files.pythonhosted.org/packages/e1/cb/8f0a75733fbac873145cd73fdb7f3eb4f6a0aac15f8d067ccae92e374ebf/watchdog-7.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:a6a34f4da483edd01c35002c204148c6bd7a0b0a5c9b35e66776d31913d4d014", size = 126033, upload-time = "2026-11-21T13:20:42.859Z" }, + { url = "https://files.pythonhosted.org/packages/1d/56/ffc8d4752673d9844b33292351ec221e6b0a7c93e6783d0d03525511ab53/watchdog-7.1.1-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:507a75e3df6f9ab8a063d3660424f09a0d6fa99b45fc91017a0898494da82c31", size = 135272, upload-time = "2026-11-21T13:20:43.874Z" }, + { url = "https://files.pythonhosted.org/packages/64/4c/8404aa06ec9b1ba070a8e22b491a40b6b7bacec2e7dcc0174a1f339eb158/watchdog-7.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:97cef4d4cfb4526f2dd215cbbfe3cafda1a22d7d1227e7da49a021cb537dc39c", size = 125829, upload-time = "2026-11-21T13:20:44.863Z" }, + { url = "https://files.pythonhosted.org/packages/55/1e/b79d61c71cdd29d187f6b8f80a9d9e8b3619b3d068eea8f834f091f98e17/watchdog-7.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:81ebb0e3ed6ec1d546498908a365fcd702db34cf096b8be88c239565c9668892", size = 126388, upload-time = "2026-11-21T13:20:45.723Z" }, + { url = "https://files.pythonhosted.org/packages/02/9d/1b7d8c08f351d55d4713d1f92ce79b4fc64f4a94182e30365b71112447c0/watchdog-7.1.1-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:d03720ed1d49845437cb8c1dd91eb04269ad031edcd3b85b28687bdc59a91207", size = 124526, upload-time = "2026-11-21T13:20:46.745Z" }, + { url = "https://files.pythonhosted.org/packages/9e/ef/50f2e5aba1029f799434c8c317a6508ddbdffd9be0f250c64468727e599e/watchdog-7.1.1-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:61821b550c888f2268090a7b590d11506fcee98a41254fe69d8bfc94660feac2", size = 125039, upload-time = "2026-11-21T13:20:47.699Z" }, + { url = "https://files.pythonhosted.org/packages/c9/85/3a4e98a5dbd859b2f0d99dd8bd1f76724c0bb3a9d8e90a1fa9998dd998fe/watchdog-7.1.1-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:3b4deb56b2245715f48fb4355fe6ba2bc02ad55384aaadc280a9a832d7cd6a80", size = 124678, upload-time = "2026-11-21T13:20:48.626Z" }, + { url = "https://files.pythonhosted.org/packages/fd/1d/99943b9510bb7c93805279a6645a6bbb4778c525c7b4635debe52db14d70/watchdog-7.1.1-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:e578a70a2f3ba5098be61c41d45ceff3d377436d18e18ee709424229ffb3825a", size = 125136, upload-time = "2026-11-21T13:20:49.516Z" }, + { url = "https://files.pythonhosted.org/packages/2f/8b/4492e6b3021d4f11179544afcfc746c19065c8ce3ffaf4e5753be43719f1/watchdog-7.1.1-py3-none-manylinux2014_aarch64.whl", hash = "sha256:6d23d2423ab0043a2aa10a758a848f4d0b36d90d9c774b168d6988c51718ba14", size = 116070, upload-time = "2026-11-21T13:20:50.817Z" }, + { url = "https://files.pythonhosted.org/packages/94/5b/84e4b280f603cc04b69927aa72d35077f59d34b4f13248025a2ae26a0e5b/watchdog-7.1.1-py3-none-manylinux2014_armv7l.whl", hash = "sha256:142578ea0aa0b9d607d508b0490d8591ae1b6852de8bd15bc23ee495c50a6a0e", size = 116069, upload-time = "2026-11-21T13:20:51.766Z" }, + { url = "https://files.pythonhosted.org/packages/62/45/f9eabc2b66967a1a2864861f4c1c2666cfe6616db55a738393fa35380b47/watchdog-7.1.1-py3-none-manylinux2014_i686.whl", hash = "sha256:9e8f9bd6d83d8231895be3a5bd8e5941520a35d9200444b87c824c54656e6a64", size = 116071, upload-time = "2026-11-21T13:20:52.658Z" }, + { url = "https://files.pythonhosted.org/packages/ec/00/b6789733bdd9183b51d55e0bba94c6994c9987cd871673f1a1680444d326/watchdog-7.1.1-py3-none-manylinux2014_ppc64.whl", hash = "sha256:48fea86f6656f64276146d256dbed92ed81bfc0b298b45266a633985d860ce0c", size = 116068, upload-time = "2026-11-21T13:20:53.921Z" }, + { url = "https://files.pythonhosted.org/packages/61/d4/cc19a0af97afc5819d6e801f2cf602e99782727c2f76a6ec8123e54b7819/watchdog-7.1.1-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:eef947410157eabb213dd987c04b102b2f4769c3e4d86b627d80a2d35ceba224", size = 116070, upload-time = "2026-11-21T13:20:54.973Z" }, + { url = "https://files.pythonhosted.org/packages/a2/44/947083ca5a5f5b3331675e7a2b71c1c67b04987059151d25c435f5d0be8d/watchdog-7.1.1-py3-none-manylinux2014_s390x.whl", hash = "sha256:9d1f0fb994d983bee5240fc2ec4bf4d2a7d08e15e3104c6d476cb7ccebf3f6b7", size = 116070, upload-time = "2026-11-21T13:20:55.944Z" }, + { url = "https://files.pythonhosted.org/packages/92/42/5c077602018b6c5a2881d7044170c2bba85c2c69d518c575da4cfe39d8f4/watchdog-7.1.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:3bc20dfaf25567fff733f9108f74fda0a32925975ed9bc07118f153730ae5f6f", size = 116071, upload-time = "2026-11-21T13:20:56.837Z" }, + { url = "https://files.pythonhosted.org/packages/aa/dc/e0c1b7b9f5c90cd8181ebcc40305dce50a3468b9147d43b0292b4a8f80ef/watchdog-7.1.1-py3-none-manylinux_2_17_aarch64.whl", hash = "sha256:507ac844f6f9d070e869f0967601c83a962f7ce138c227592bdf6e70e65ce5aa", size = 116073, upload-time = "2026-11-21T13:20:58.038Z" }, + { url = "https://files.pythonhosted.org/packages/56/fb/8005d322c1f5e2343fb606ddd945fb8a2bf815dc62b76132465ceafd515e/watchdog-7.1.1-py3-none-manylinux_2_17_armv7l.whl", hash = "sha256:0c08c2a48f97ecd3b6512e826472e04c488e7d5c4dd1189ac2854f98eee24f5a", size = 116070, upload-time = "2026-11-21T13:20:59.458Z" }, + { url = "https://files.pythonhosted.org/packages/c9/69/3f84271c0f270da403982c869b0f3e4762301f8646d342734b0551a4062e/watchdog-7.1.1-py3-none-manylinux_2_17_i686.whl", hash = "sha256:1f44c085c768470930ebfa31c7159dd506fb11cf1db0761fbf57922f59b528e7", size = 116071, upload-time = "2026-11-21T13:21:00.664Z" }, + { url = "https://files.pythonhosted.org/packages/2b/e6/9319ac4b2aa5242bcb5adde55e16107fa01f86befb4eb502b82d9d1a30aa/watchdog-7.1.1-py3-none-manylinux_2_17_ppc64.whl", hash = "sha256:3287e8f628a1c333c342898c827aa32554921f031e0d9b1c56122c24ff1cf590", size = 116070, upload-time = "2026-11-21T13:21:01.936Z" }, + { url = "https://files.pythonhosted.org/packages/3d/ee/46c6c9ac3c1877f5573ebe4d2f6cee938ae0cc284a7c2305fdd76a35576b/watchdog-7.1.1-py3-none-manylinux_2_17_ppc64le.whl", hash = "sha256:f221e03057394041166cf0562d4a7bdc19330a68e3b852f4df208e4889b0e175", size = 116070, upload-time = "2026-11-21T13:21:02.92Z" }, + { url = "https://files.pythonhosted.org/packages/2f/f9/0dc040642135ae0e74f25ac72f2a1daad2cbd278729781a90227cdd04954/watchdog-7.1.1-py3-none-manylinux_2_17_s390x.whl", hash = "sha256:0a1a1b53d30f158ea85459c7aaa5f746eabe2d4cf6e15273c8a0e9d0bb53157e", size = 116070, upload-time = "2026-11-21T13:21:03.914Z" }, + { url = "https://files.pythonhosted.org/packages/2a/71/982ce908118adf7c876b0946099a0cbff5cd4e22cf7ddd96ca22290df632/watchdog-7.1.1-py3-none-manylinux_2_17_x86_64.whl", hash = "sha256:32b4c6b7fa0700782756b9faf868071c2a95249bbce48df5c3e0840b98fe8af5", size = 116071, upload-time = "2026-11-21T13:21:05.199Z" }, + { url = "https://files.pythonhosted.org/packages/3c/9e/ac523c07d742bb45b463ef5d90f122a436c071068fabb229337a58bb9b02/watchdog-7.1.1-py3-none-win32.whl", hash = "sha256:5e161c1d97c6a9140e6713b75eb5811845998cf8f57e02c23444e6951488524c", size = 116058, upload-time = "2026-11-21T13:21:06.285Z" }, + { url = "https://files.pythonhosted.org/packages/31/57/ff9edd8e7c1b9a0749c5db4dd154667140a3b8414659960fe182d18d6b4e/watchdog-7.1.1-py3-none-win_amd64.whl", hash = "sha256:f6e0da274cc1610b37ff7afe0c2a2b454308a0684efea0bfb7bedaa530b08106", size = 116063, upload-time = "2026-11-21T13:21:07.254Z" }, + { url = "https://files.pythonhosted.org/packages/07/af/1022a429f58cd84302a5b9aca7c78e22078867f30eab862eccdcbfd601c5/watchdog-7.1.1-py3-none-win_arm64.whl", hash = "sha256:7bc7f4389b1634e874ffd0d6c84c9680c6adbb48c3aece8e087bb25ee9b93f0e", size = 116062, upload-time = "2026-11-21T13:21:08.204Z" }, + { url = "https://files.pythonhosted.org/packages/4d/ff/bd007a0bded2f68bf2f23c28eae1e0567cbd8a2e80ea4f217ebc359ce4d0/watchdog-7.1.1-py3-none-win_ia64.whl", hash = "sha256:31a0e81dca2cbe5f1f2d46906277ae3aeb64cf9506d60cf10fa9ad00cbdaa6c8", size = 116060, upload-time = "2026-11-21T13:21:09.168Z" }, +] + [[package]] name = "zarr-storage" source = { editable = "." } @@ -252,6 +1000,15 @@ testing = [ ] [package.dev-dependencies] +docs = [ + { name = "griffe-inherited-docstrings" }, + { name = "mkdocs" }, + { name = "mkdocs-material" }, + { name = "mkdocstrings" }, + { name = "mkdocstrings-python" }, + { name = "pymdown-extensions" }, + { name = "ruff" }, +] test = [ { name = "hypothesis" }, { name = "obstore" }, @@ -268,6 +1025,15 @@ requires-dist = [ provides-extras = ["obstore", "testing"] [package.metadata.requires-dev] +docs = [ + { name = "griffe-inherited-docstrings", specifier = "==1.1.3" }, + { name = "mkdocs", specifier = "==1.6.1" }, + { name = "mkdocs-material", specifier = "==9.7.7" }, + { name = "mkdocstrings", specifier = "==1.0.6" }, + { name = "mkdocstrings-python", specifier = "==2.0.8" }, + { name = "pymdown-extensions", specifier = "==11.0.1" }, + { name = "ruff", specifier = "==0.16.8" }, +] test = [ { name = "hypothesis", specifier = ">=6.85" }, { name = "obstore", specifier = ">=0.12" }, From 2ff082e9676479b80ef730024c9c4d66adaf2c23 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 20:25:37 +0100 Subject: [PATCH 13/31] fix(zarr-storage): take limiter slots before work goes to the pool A sync backend's operation through an `AsyncStore`, and each operation of a `Store` batch, took its slot on the pool thread that ran it. A burst on a `limited(1)` view then parked every pool thread waiting for that one slot, stalling every other store on the pool, and a write cancelled while it waited still ran later, overwriting newer writes. Slots are now taken by whoever hands work to the pool (the task, or the batch's calling thread) and given back by the pool thread when the work finishes, so pool threads never wait for slots. `ThreadPool.run` never starts cancelled work that is still queued, waits for cancelled work already running before propagating the cancellation, and runs inline on its own threads. A batch cancels its queued operations after the first failure. A thread interrupted while waiting for a slot gives the slot back, and a pickled derived view stays derived instead of becoming the backend's owner. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../zarr-storage/src/zarr_storage/_batch.py | 73 +++++++-- .../src/zarr_storage/_resources.py | 49 +++++- .../zarr-storage/src/zarr_storage/_store.py | 62 ++++---- packages/zarr-storage/tests/test_batch.py | 34 +++- packages/zarr-storage/tests/test_resources.py | 150 +++++++++++++++++- packages/zarr-storage/tests/test_store.py | 13 ++ 6 files changed, 325 insertions(+), 56 deletions(-) diff --git a/packages/zarr-storage/src/zarr_storage/_batch.py b/packages/zarr-storage/src/zarr_storage/_batch.py index c3a9145599..70e53ccb7d 100644 --- a/packages/zarr-storage/src/zarr_storage/_batch.py +++ b/packages/zarr-storage/src/zarr_storage/_batch.py @@ -2,8 +2,14 @@ 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, lets the running ones finish (yielding those that succeed), then raises -an `ExceptionGroup` of every failure. `Store` turns that group into a `BatchError`. +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`. + +`run_many` holds a slot of its `limiter` for each operation. It takes the slot on the calling +thread before the operation goes to the pool, and the pool thread gives it back when the operation +finishes, so pool threads never wait for slots: a narrowly limited batch can't park the threads +every other user of the pool needs. """ from __future__ import annotations @@ -16,7 +22,7 @@ from collections.abc import AsyncIterator, Callable, Coroutine, Iterator, Sequence from concurrent.futures import Future - from zarr_storage._resources import ThreadPool + from zarr_storage._resources import Limiter, Slot, ThreadPool __all__ = ["run_many", "run_many_async"] @@ -31,23 +37,47 @@ def run_many( requests: Sequence[tuple[*Ts]], pool: ThreadPool | None = None, window: int = 1, + limiter: Limiter | None = None, ) -> Iterator[tuple[int, R]]: - """Call `fn(*request)` for each request: one at a time, or on `pool`, `window` at once. + """Call `fn(*request)` for each request: one at a time, or on `pool`, `window` at once, each + holding a slot of `limiter` if one is given. 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) + return _run_serially(fn, requests, limiter) + return _run_on(pool, fn, requests, window, limiter) + + +def _take(limiter: Limiter | None) -> Slot | None: + """A slot of `limiter`, entered on the calling thread; `None` without a limiter.""" + if limiter is None: + return None + slot = limiter.slot() + slot.__enter__() + return slot + + +def _give_back(slot: Slot | None) -> None: + if slot is not None: + slot.__exit__(None, None, None) + + +def _holding(slot: Slot | None, fn: Callable[[Unpack[Ts]], R], *args: *Ts) -> R: + """`fn(*args)`, then give back `slot`, which the submitting thread took.""" + try: + return fn(*args) + finally: + _give_back(slot) def _run_serially( - fn: Callable[[Unpack[Ts]], R], requests: Sequence[tuple[*Ts]] + fn: Callable[[Unpack[Ts]], R], requests: Sequence[tuple[*Ts]], limiter: Limiter | None ) -> Iterator[tuple[int, R]]: for index, request in enumerate(requests): try: - result = fn(*request) + result = _holding(_take(limiter), fn, *request) except Exception as error: # noqa: BLE001 -- every failure is reported, in the group raise ExceptionGroup(_MESSAGE, [error]) from None yield index, result @@ -58,18 +88,25 @@ def _run_on( fn: Callable[[Unpack[Ts]], R], requests: Sequence[tuple[*Ts]], window: int, + limiter: Limiter | None, ) -> Iterator[tuple[int, R]]: - pending: dict[Future[R], int] = {} + pending: dict[Future[R], tuple[int, Slot | None]] = {} 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 + slot = _take(limiter) + try: + future = pool.submit(_holding, slot, fn, *requests[started]) + except BaseException: + _give_back(slot) + raise + pending[future] = (started, slot) started += 1 done, _ = wait(pending, return_when=FIRST_COMPLETED) for future in done: - index = pending.pop(future) + index, _slot = pending.pop(future) error = future.exception() if error is None: yield index, future.result() @@ -77,13 +114,23 @@ def _run_on( errors.append(error) else: raise error + if errors: + _cancel_queued(pending) finally: - for future in pending: - future.cancel() + _cancel_queued(pending) if errors: raise ExceptionGroup(_MESSAGE, errors) +def _cancel_queued(pending: dict[Future[R], tuple[int, Slot | None]]) -> None: + """Cancel the operations in `pending` that haven't started, giving back their slots; those + running stay, and give back their own.""" + for future, (_index, slot) in list(pending.items()): + if future.cancel(): + del pending[future] + _give_back(slot) + + async def run_many_async( fn: Callable[[Unpack[Ts]], Coroutine[Any, Any, R]], requests: Sequence[tuple[*Ts]], diff --git a/packages/zarr-storage/src/zarr_storage/_resources.py b/packages/zarr-storage/src/zarr_storage/_resources.py index ca9c9e8ec5..ffdfd9d2b3 100644 --- a/packages/zarr-storage/src/zarr_storage/_resources.py +++ b/packages/zarr-storage/src/zarr_storage/_resources.py @@ -23,7 +23,6 @@ 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 @@ -128,10 +127,23 @@ def submit(self, fn: Callable[[*Ts], R], /, *args: *Ts) -> Future[R]: 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.""" - context = contextvars.copy_context() - loop = asyncio.get_running_loop() - return await loop.run_in_executor(self._pool(), partial(context.run, fn, *args)) + """Await `fn(*args)`, run on one of the pool's threads. + + If the awaiting task is cancelled, work that has not started never runs, and work that has + started finishes before the cancellation propagates: once a cancelled `run` returns, the + work has no further effect. 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. + """ + if self.in_worker(): + return fn(*args) + future = self.submit(fn, *args) + try: + return await asyncio.wrap_future(future) + except asyncio.CancelledError: + if not future.cancel(): + await _finish(future) + raise def shutdown(self, *, wait: bool = True) -> None: """Stop the pool's threads; with `wait`, after the work already given them. @@ -145,6 +157,20 @@ def shutdown(self, *, wait: bool = True) -> None: executor.shutdown(wait=wait) +async def _finish(future: Future[R]) -> None: + """Wait until `future`, already running, is done, through any further cancellation.""" + inner = asyncio.wrap_future(future) + while not inner.done(): + try: + await asyncio.shield(inner) + except asyncio.CancelledError: + continue + except BaseException: # noqa: BLE001 -- the work's own failure; the cancellation propagates + break + if not inner.cancelled(): + inner.exception() # retrieved, so it is not reported as never retrieved + + class _DefaultThreadPool(ThreadPool): """The process-wide pool: never shut down, and unpickled as the receiver's own default.""" @@ -290,7 +316,18 @@ def acquire(self) -> None: return waiter = _ThreadWaiter() self._waiters.append(waiter) - waiter.wait() + 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.""" diff --git a/packages/zarr-storage/src/zarr_storage/_store.py b/packages/zarr-storage/src/zarr_storage/_store.py index 6d443a84bb..8ae7e1b462 100644 --- a/packages/zarr-storage/src/zarr_storage/_store.py +++ b/packages/zarr-storage/src/zarr_storage/_store.py @@ -6,16 +6,16 @@ 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. +A slot is taken by whoever hands work to the pool, before handing it over, and given back when the +work finishes: an `AsyncStore` takes it in its task, and a `Store` batch on its calling thread. Pool +threads never wait for slots, so a narrowly limited burst can't park the threads every other user +of the pool needs, and a cancelled operation that was still waiting for its slot never runs. """ from __future__ import annotations from collections.abc import AsyncGenerator, Generator -from typing import TYPE_CHECKING, Final, Generic, Self, TypeVar, TypeVarTuple, cast, final +from typing import TYPE_CHECKING, Any, Final, Generic, Self, TypeVar, TypeVarTuple, cast, final from zarr_storage._batch import run_many, run_many_async from zarr_storage._buffers import byte_view @@ -80,12 +80,6 @@ """A `get_many` request: a key, or a key and the part of its value to read.""" -def _limited(limiter: Limiter, fn: Callable[[*Ts], R], *args: *Ts) -> R: - """`fn(*args)`, holding a slot of `limiter`, on the calling thread.""" - with limiter.slot(): - return fn(*args) - - def _list_all(fn: Callable[[str], Iterator[T]], directory: str) -> list[T]: return list(fn(directory)) @@ -189,10 +183,21 @@ def __repr__(self) -> str: def __reduce__(self) -> tuple[object, ...]: return ( - _restore_store, - (type(self), self._backend, self._root, self._read_only, self._context), + 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. + store = cls(cast("Any", backend), root=root, read_only=read_only, context=context) + store._owner = owner + return store + # ----------------------------------------------------------------- path handling def _check_open(self) -> None: @@ -339,8 +344,11 @@ def __exit__( 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) + """`fn` over `requests` on the context's pool, at most the limiter's limit at once, each + holding a slot of the limiter.""" + return run_many( + fn, requests, self._context.threads, self._limiter.limit, limiter=self._limiter + ) def _streamed( self, batch: Sequence[T], results: Iterator[tuple[int, R]] @@ -513,7 +521,7 @@ def get_many( 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)) + return self._streamed(batch, self._run_many(backend.get, paths)) def get_into_many( self: Store[ReadableInto[O]], @@ -530,7 +538,7 @@ def get_into_many( 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)) + return self._streamed(batch, self._run_many(backend.get_into, paths)) def put_many( self: Store[Writable], items: Iterable[tuple[str, Buffer]] @@ -546,7 +554,7 @@ def put_many( 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)) + return self._finished(keys, self._run_many(backend.put, requests)) def delete_many( self: Store[Writable], keys: Iterable[str] @@ -557,7 +565,7 @@ def delete_many( 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])) + return self._finished(batch, self._run_many(backend.delete, [(path,) for path in paths])) # ----------------------------------------------------------------- listing @@ -657,8 +665,14 @@ async def __aexit__( # ----------------------------------------------------------------- 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.""" - return await self._context.threads.run(_limited, self._limiter, fn, *args) + """`fn(*args)` on the context's pool, holding a slot taken here, before the work goes to + the pool. + + If the task is cancelled while it waits for the slot or for a thread, `fn` never runs; once + `fn` is running, the cancellation waits for it to finish, so the slot covers it throughout. + """ + async with self._slot(): + return await self._context.threads.run(fn, *args) async def _streamed( self, batch: Sequence[T], results: AsyncIterator[tuple[int, R]] @@ -972,9 +986,3 @@ def _batch_error( async def _relativized(paths: AsyncIterator[str], root: str) -> AsyncIterator[str]: async for path in paths: yield relativize(path, root) - - -def _restore_store( - cls: type[_View[Backend]], backend: Backend, root: str, read_only: bool, context: Context -) -> _View[Backend]: - return cls(backend, root=root, read_only=read_only, context=context) diff --git a/packages/zarr-storage/tests/test_batch.py b/packages/zarr-storage/tests/test_batch.py index c88d7918bc..46e6e8fce4 100644 --- a/packages/zarr-storage/tests/test_batch.py +++ b/packages/zarr-storage/tests/test_batch.py @@ -11,7 +11,7 @@ from zarr_storage import BatchError from zarr_storage._batch import run_many, run_many_async -from zarr_storage._resources import ThreadPool +from zarr_storage._resources import Limiter, ThreadPool if TYPE_CHECKING: from collections.abc import AsyncIterator @@ -94,14 +94,40 @@ def test_runner(mode: str, window: int, n: int) -> None: @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.""" + """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 tracker.started == set(range(window)) - assert sorted(results) == [(x, x * x) for x in range(1, window)] + assert 0 in tracker.started + assert tracker.started <= set(range(window)) + assert sorted(results) == [(x, x * x) for x in sorted(tracker.started - {0})] + + +@pytest.mark.parametrize("fails", [None, 0]) +def test_runner_on_a_pool_gives_back_every_slot(fails: int | None) -> None: + """Slots are taken before work is queued on the pool; work cancelled after a failure, and work + that ran, give theirs back.""" + tracker = _Tracker(fails=fails) + limiter = Limiter(4) + pool = ThreadPool(1) + requests = [(x,) for x in range(8)] + results: list[tuple[int, int]] = [] + try: + if fails is None: + results.extend(run_many(tracker, requests, pool, 4, limiter=limiter)) + else: + with pytest.raises(ExceptionGroup): + results.extend(run_many(tracker, requests, pool, 4, limiter=limiter)) + finally: + pool.shutdown() + assert limiter.in_use == 0 + assert tracker.started == ({0} if fails == 0 else set(range(8))) def test_batch_error_keeps_its_report_when_split() -> None: diff --git a/packages/zarr-storage/tests/test_resources.py b/packages/zarr-storage/tests/test_resources.py index aa6d925bb9..5099866a82 100644 --- a/packages/zarr-storage/tests/test_resources.py +++ b/packages/zarr-storage/tests/test_resources.py @@ -6,14 +6,14 @@ import pickle import threading import time -from functools import partial +from functools import partial, partialmethod from typing import TYPE_CHECKING import pytest from obstore.store import MemoryStore -from zarr_storage import Context, Found, Limiter, Missing, Store, ThreadPool -from zarr_storage._resources import default_limiter +from zarr_storage import AsyncStore, Context, Found, Limiter, Missing, Store, ThreadPool +from zarr_storage._resources import _ThreadWaiter, default_limiter from zarr_storage.backends import LocalBackend, MemoryBackend, ObjectStoreBackend if TYPE_CHECKING: @@ -192,6 +192,31 @@ 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): @@ -226,6 +251,64 @@ def test_thread_pool_of_a_bad_size_raises(size: object, error: type[Exception]) ThreadPool(size) # pyright: ignore[reportArgumentType] +def _wait_then_record(gate: threading.Event, ran: list[str], name: str) -> None: + gate.wait() + ran.append(name) + + +async def _cancel_runs(pool: ThreadPool) -> tuple[list[str], list[str]]: + """Cancel one `run` whose work hasn't started and one whose work is running; return what ran + by the time each cancellation finished.""" + ran: list[str] = [] + busy, started = threading.Event(), threading.Event() + pool.submit(busy.wait) # holds the only thread, so the next run is queued + queued = asyncio.ensure_future(pool.run(ran.append, "queued")) + await asyncio.sleep(0.05) + queued.cancel() + with pytest.raises(asyncio.CancelledError): + await queued + busy.set() + gate = threading.Event() + running = asyncio.ensure_future(pool.run(_started_then, started, gate, ran)) + await asyncio.to_thread(started.wait) + running.cancel() + threading.Timer(0.05, gate.set).start() + with pytest.raises(asyncio.CancelledError): + await running + after_running = list(ran) + await asyncio.sleep(0.05) + return after_running, ran + + +def _started_then(started: threading.Event, gate: threading.Event, ran: list[str]) -> None: + started.set() + _wait_then_record(gate, ran, "running") + + +def test_cancelled_run_never_starts_queued_work_and_waits_for_running_work() -> None: + """Once a cancelled `run` returns, its work has either not run at all or already finished.""" + pool = ThreadPool(1) + try: + after_running, finally_ran = asyncio.run(_cancel_runs(pool)) + finally: + pool.shutdown() + assert after_running == ["running"] + assert finally_ran == ["running"] + + +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() @@ -403,12 +486,13 @@ def _settle() -> None: time.sleep(0.05) -def test_async_read_of_a_sync_backend_holds_no_slot_while_it_waits_for_a_thread( +def test_sync_batch_and_async_read_sharing_one_thread_and_one_slot_both_finish( 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.""" + sync backend is queued behind it. Neither may wait forever for the other: slots are taken + before work goes to the pool, so the batch's read holds the slot while it waits for the thread, + and the async read waits for the slot without holding the thread.""" pool, limiter = ThreadPool(1), Limiter(1) store = Store(LocalBackend(tmp_path), context=Context(threads=pool, limits={"local": limiter})) store.put("k", b"x") @@ -429,3 +513,57 @@ def test_async_read_of_a_sync_backend_holds_no_slot_while_it_waits_for_a_thread( assert not async_reader.is_alive() assert [type(r) for r in batch + single] == [Found, Found] assert limiter.in_use == 0 + + +class _SlowLocalBackend(LocalBackend): + def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: + time.sleep(0.2) + return super().get(path, byte_range) + + +async def _burst_and_probe( + burst: AsyncStore[LocalBackend], other: AsyncStore[LocalBackend] +) -> float: + reads = [asyncio.ensure_future(burst.get("k")) for _ in range(6)] + await asyncio.sleep(0.05) # the burst is under way + start = time.monotonic() + assert isinstance(await other.get("k"), Found) + waited = time.monotonic() - start + await asyncio.gather(*reads) + return waited + + +def test_narrowly_limited_burst_leaves_the_pool_to_others(tmp_path: Path) -> None: + """Six slow reads through a `limited(1)` view of a sync backend occupy one pool thread, not + all of them, so another store on the same pool isn't queued behind the burst.""" + pool = ThreadPool(2) + context = Context(threads=pool) + slow = AsyncStore(_SlowLocalBackend(tmp_path / "slow"), context=context) + other = AsyncStore(LocalBackend(tmp_path / "other"), context=context) + try: + slow.as_sync().put("k", b"x") + other.as_sync().put("k", b"x") + waited = asyncio.run(_burst_and_probe(slow.limited(1), other)) + finally: + pool.shutdown() + assert waited < 0.15 + + +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) diff --git a/packages/zarr-storage/tests/test_store.py b/packages/zarr-storage/tests/test_store.py index 15d1f4eaa1..1a988b75f0 100644 --- a/packages/zarr-storage/tests/test_store.py +++ b/packages/zarr-storage/tests/test_store.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import pickle from typing import TYPE_CHECKING import pytest @@ -340,3 +341,15 @@ async def _static_surface_checks( 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 From 95b83c6515bc3472d7d669a26e2093380497c8f6 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 20:27:24 +0100 Subject: [PATCH 14/31] fix(zarr-storage): stop LocalBackend's delete_dir and listings at symlinked directories `delete_dir` checked only the last component for a symlink, so `delete_dir("link/sub")` deleted `sub` in whatever directory `link` pointed to, outside the root. `delete_dir`, `list` and `list_dir` now treat a symlink anywhere between the root and their target as the end of the tree, and listings report only what `get` reads as a key: regular files and symlinks to them, not symlinks to directories, dangling symlinks or special files. Also: a write that fails while staging (a full disk, an interrupt) removes its partial file; reserved names are refused in any case, as case-insensitive filesystems read them; a write under a dangling symlink raises `KeyConflictError` instead of retrying 64 times; and a root that is a file raises `NotADirectoryError` saying so. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../src/zarr_storage/backends/_local.py | 74 +++++++++++++++---- packages/zarr-storage/tests/test_local.py | 62 +++++++++++++++- 2 files changed, 118 insertions(+), 18 deletions(-) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index 9521876845..ddbdae1c85 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -129,8 +129,10 @@ def segment_problem(segment: str, *, windows: bool) -> str | None: characters, device names such as `NUL` or `com1.txt`, and names ending in `.` or a space, which Windows strips. """ - if segment.endswith(RESERVED_SUFFIX): - return f"names ending in {RESERVED_SUFFIX!r} are reserved by the local backend" + 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): @@ -142,6 +144,11 @@ def segment_problem(segment: str, *, windows: bool) -> str | None: 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) @@ -398,6 +405,8 @@ def __init__( create: bool = True, ) -> None: self._root = Path(root).resolve() + if self._root.exists() and not self._root.is_dir(): + raise NotADirectoryError(f"The root {str(self._root)!r} is a file, not a directory.") if create: self._root.mkdir(parents=True, exist_ok=True) elif not self._root.is_dir(): @@ -585,10 +594,17 @@ def _stage(self, value: memoryview) -> tuple[Path, Generation]: try: staging.mkdir(parents=True, exist_ok=True) with open(temp, "xb") as f: - f.write(value) - f.flush() - _set_mtime(f.fileno(), temp, _unique_stamp()) - staged = _generation(os.fstat(f.fileno())) + 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( @@ -603,10 +619,11 @@ def _stage(self, value: memoryview) -> tuple[Path, Generation]: return temp, staged def _has_key_parent(self, file: Path) -> bool: - """Whether a directory between the root and `file` is a regular file (a key).""" + """Whether a directory between the root and `file` is a regular file (a key), or a + dangling symlink, which no write can turn into a directory.""" parent = file.parent while parent != self._root: - if _stat_key(parent) is not None: + if _stat_key(parent) is not None or (parent.is_symlink() and not parent.exists()): return True parent = parent.parent return False @@ -628,7 +645,8 @@ def _commit( except (FileExistsError, NotADirectoryError) as e: if self._has_key_parent(file): raise KeyConflictError( - f"A parent of {path!r} is a key, so it can't also be a directory." + f"A parent of {path!r} is a key (or a 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. @@ -672,20 +690,36 @@ def delete_dir(self, directory: str) -> None: with _key_errors(directory): if target == self._root: _remove_tree(self._root, remove_self=False) - elif target.is_dir() and not target.is_symlink(): + elif not self._through_symlink(target) and target.is_dir(): _remove_tree(target, remove_self=True) + 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: + if target.is_symlink(): + 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): @@ -699,24 +733,36 @@ def _walk(directory: Path, prefix: str) -> Iterator[str]: except (FileNotFoundError, NotADirectoryError): return for entry in entries: - if entry.name.endswith(RESERVED_SUFFIX): + if _is_reserved(entry.name): continue if entry.is_dir(follow_symlinks=False): yield from _walk(Path(entry.path), f"{prefix}{entry.name}/") - else: + elif _is_key_file(entry): yield f"{prefix}{entry.name}" def _classify(entries: list[os.DirEntry[str]]) -> Iterator[ListItem]: for entry in entries: - if entry.name.endswith(RESERVED_SUFFIX): + if _is_reserved(entry.name): continue if entry.is_dir(follow_symlinks=False): yield Prefix(entry.name) - else: + elif _is_key_file(entry): yield Key(entry.name) +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 diff --git a/packages/zarr-storage/tests/test_local.py b/packages/zarr-storage/tests/test_local.py index 2699181b86..5eed4232c6 100644 --- a/packages/zarr-storage/tests/test_local.py +++ b/packages/zarr-storage/tests/test_local.py @@ -77,6 +77,21 @@ def test_failed_put_leaves_no_staged_files(tmp_path: Path) -> None: 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.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") @@ -108,6 +123,7 @@ def test_put_recreates_a_removed_root(tmp_path: Path) -> 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"), @@ -135,6 +151,13 @@ def test_missing_root_without_create_raises(tmp_path: Path) -> None: LocalBackend(tmp_path / "missing", create=False) +@pytest.mark.parametrize("create", [True, False]) +def test_root_that_is_a_file_raises(tmp_path: Path, create: bool) -> None: + (tmp_path / "file").write_bytes(b"x") + with pytest.raises(NotADirectoryError, match="is a file"): + LocalBackend(tmp_path / "file", create=create) + + 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") @@ -312,14 +335,45 @@ def test_delete_dir_waits_for_a_write_in_progress( assert isinstance(store.put_if_absent("P/D/k", b"y"), Written) -def test_delete_dir_leaves_a_symlinked_directory_alone(tmp_path: Path) -> None: +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.mkdir() - (outside / "keep").write_bytes(b"x") + (outside / "sub").mkdir(parents=True) + (outside / "sub" / "keep").write_bytes(b"x") store = Store(LocalBackend(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 / "keep").exists() + assert (outside / "sub" / "keep").exists() + + +def test_symlink_to_a_file_is_a_key(tmp_path: Path) -> None: + (tmp_path / "target").write_bytes(b"x") + store = Store(LocalBackend(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(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_dangling_symlink_raises(tmp_path: Path) -> None: + store = Store(LocalBackend(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: From a1ce8921080e0aeff08d3f95657c31c3f182dbcc Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 20:28:04 +0100 Subject: [PATCH 15/31] fix(zarr-storage): never answer Unchanged for an obstore generation that identifies no value A store that reports neither an ETag nor a version (an HTTP server that sends no ETag) gave every value the generation `("obstore", None, None)`, so `get_if_changed` read the new bytes, found the generations equal, and discarded them as `Unchanged`. Such a generation now never reads as unchanged. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../src/zarr_storage/backends/_obstore.py | 12 ++++++-- packages/zarr-storage/tests/test_obstore.py | 28 +++++++++++++++++-- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py index e2038b06a3..ff9f048d2e 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py @@ -815,10 +815,16 @@ def _unless_unchanged( ) -> Found | Missing | Unchanged: """`Unchanged` for a value read whole although it has `generation`. - That happens when the store can't skip the read (no ETag to send, or it ignores - `If-None-Match`); the bytes are discarded so the outcome doesn't depend on the store. + 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: + 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 diff --git a/packages/zarr-storage/tests/test_obstore.py b/packages/zarr-storage/tests/test_obstore.py index 213203297a..82edcd6f10 100644 --- a/packages/zarr-storage/tests/test_obstore.py +++ b/packages/zarr-storage/tests/test_obstore.py @@ -8,7 +8,7 @@ from obstore.exceptions import GenericError from obstore.store import LocalStore, MemoryStore -from zarr_storage import Found, ObjectMetadata, RangeRequest, Store, Unchanged +from zarr_storage import Found, Generation, ObjectMetadata, RangeRequest, Store, Unchanged from zarr_storage.backends import ObjectStoreBackend from zarr_storage.backends import _obstore as obstore_backend from zarr_storage.backends._obstore import _empty_read_or_raise, _generation @@ -182,8 +182,8 @@ def _no_if_none_match(generation: object) -> dict[str, str]: 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 (no ETag, or it ignores `If-None-Match`) still reports - `Unchanged` for a value that has the generation.""" + """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 @@ -192,3 +192,25 @@ def test_get_if_changed_without_if_none_match_is_unchanged( 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" From e4e1c33a7eb01e408ff23bd67ca80a6d564ceafc Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 20:32:39 +0100 Subject: [PATCH 16/31] docs(zarr-storage): make DESIGN.md match the code and stand on its own upstream Drop references to private planning documents and prototypes; list every capability protocol and conformance mixin under its right heading; say that native batches draw on the context themselves; describe the new slot, cancellation and symlink rules and the obstore generations that identify no value; and list the known gaps under "Open". Give every capability protocol a docstring, type `shares_backend`/`overlaps` with the public store classes, export `Slot`, and merge the fork's two changelog fragments into one, to be numbered after the upstream pull request. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/DESIGN.md | 78 ++++++++++++------- packages/zarr-storage/changes/460.feature.md | 1 - packages/zarr-storage/changes/464.feature.md | 1 - packages/zarr-storage/changes/PR.feature.md | 1 + .../zarr-storage/src/zarr_storage/__init__.py | 3 +- .../src/zarr_storage/_protocols.py | 37 +++++++++ .../zarr-storage/src/zarr_storage/_store.py | 4 +- packages/zarr-storage/tests/test_batch.py | 8 +- packages/zarr-storage/tests/test_resources.py | 2 +- 9 files changed, 101 insertions(+), 34 deletions(-) delete mode 100644 packages/zarr-storage/changes/460.feature.md delete mode 100644 packages/zarr-storage/changes/464.feature.md create mode 100644 packages/zarr-storage/changes/PR.feature.md diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 0867b09478..0dccaa64df 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -1,23 +1,23 @@ # zarr-storage design (v0) -Status: draft, 2026-11-17. This is the new storage API from the storage plan -(`proposals/store-hierarchy-layering.md` in the planning worktree). It is built in iterations; each -iteration ends with every backend passing the shared conformance suite. +Status: pre-release. This is the contract the package's code and its conformance suite implement. +It is built in iterations; each iteration ends with every backend passing the shared conformance +suite. Sources, and what each contributed: -- **zng_storage** (Davis Bennett's earlier prototype): capability protocols instead of a class - hierarchy, a sync floor with an async family beside it, generations and result types, `store / "sub"`. +- **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. -- **zarr-python-planning store proposals**: result types and `ObjectMetadata`, conditional writes that - report a refusal instead of raising, the conformance-suite layout. +- **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`). -- **The storage plan**: directory prefixes, `Key | Prefix | Entry` listing, `delete` vs `delete_dir`, +- **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. @@ -34,8 +34,9 @@ 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`, `Writable`, -`Listable`, `WritableIfMatch`, `DeletableIfMatch`, and their async twins) on *backend paths*: +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. 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 @@ -63,7 +64,7 @@ backend's `aclose` (a backend whose cleanup awaits a client session) and calls ` - **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 (as TensorStore's file driver does), names too long for the filesystem, and on + 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 @@ -122,7 +123,8 @@ works and order doesn't matter. Reads are lazy and come in the order they finish 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, lets those running finish, +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 @@ -136,8 +138,8 @@ used instead, for batching the store itself can do (one request for many keys, o 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. The batch -runners in `zarr_storage._batch` implement the windowing and failure rule once. +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`. @@ -148,6 +150,9 @@ raises `InvalidByteRangeError`; a suffix longer than the value returns the whole **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 @@ -189,8 +194,12 @@ tree bottom-up under each directory's lock, so a write in progress finishes befo 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 in a key's place is that key's -file. Each write stamps its file with a nanosecond mtime unique within the process, because +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, since +what lies beyond one may lie outside the root: listings leave such a link out, return nothing for a +directory reached through one, and `delete_dir` deletes nothing through one. Single-key operations +go through it, as the filesystem resolves the path. Dangling symlinks and special files are not +keys. 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`. @@ -208,15 +217,15 @@ writes that concurrently create and remove the same directories can surface its ## Conformance suite `zarr_storage.testing.StoreSuite` holds the contract every backend meets; optional capabilities come -as mixins a backend's test class adds (`ConditionalPutSuite`, `KeyAndDirectorySuite`, -`PickleSuite`, ...) or their refusing counterparts (`NoConditionalPutSuite`, -`KeyDirectoryConflictSuite`, `ConditionalRaceSuite`, ...). Every test runs twice: through `Store`, +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 (`zarr_storage.testing._stateful.StoreMachine`), again through both surfaces. After every +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. @@ -235,9 +244,10 @@ object-store requests by wrapping the store in object_store's `LimitStore` and s `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 through the view holds a slot of + 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`. Stores sharing a + `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 @@ -246,16 +256,23 @@ object-store requests by wrapping the store in object_store's `LimitStore` and s 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. + and **before work goes to the pool**: an `AsyncStore` takes the slot in its task, a `Store` batch + on its calling thread, and the pool thread gives it back when the work finishes. Pool threads + never wait for slots, so a narrowly limited burst occupies one thread per slot, never the whole + pool, and slot holders waiting for threads always get one. (An earlier draft took slots on the + pool threads; a `limited(1)` burst then parked every thread of the shared pool.) +- **Cancellation**: an operation cancelled while it waits for its slot or for a thread never runs; + one cancelled while running on a thread finishes before the cancellation propagates. So once a + cancelled call returns, it has no further effect. - `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: - waiting there for work queued on the same pool could wait forever once every thread does it. +- 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 @@ -345,6 +362,13 @@ resources are passed in a store's context. - 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. - Listings hold no slot of the context's limiter. +- 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- and normalization-insensitive filesystems (APFS, NTFS) store distinct keys such as `a` and + `A` in one file, 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 diff --git a/packages/zarr-storage/changes/460.feature.md b/packages/zarr-storage/changes/460.feature.md deleted file mode 100644 index 618fe3e1d8..0000000000 --- a/packages/zarr-storage/changes/460.feature.md +++ /dev/null @@ -1 +0,0 @@ -Add `zarr-storage`, a new package with a Zarr-agnostic key-value storage API: `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 (`get_if_changed`, `put_if_absent`, `put_if_match`, `delete_if_match`), byte-range reads, reads into caller buffers, and batches (`get_many`, `get_into_many`, `put_many`, `delete_many`) that run concurrently where the backend can. It ships a conformance suite in `zarr_storage.testing` that any backend can run. diff --git a/packages/zarr-storage/changes/464.feature.md b/packages/zarr-storage/changes/464.feature.md deleted file mode 100644 index 20d405e110..0000000000 --- a/packages/zarr-storage/changes/464.feature.md +++ /dev/null @@ -1 +0,0 @@ -Add `Context`, the resources a `zarr-storage` store's operations draw on: a `ThreadPool` and a `Limiter` per backend resource key, with process-wide defaults. Every store view carries a context (`Store(backend, context=...)`, `with_context`), stores sharing a context share its limits, and `store.limited(n)` bounds a burst of operations within the context's limit. `AsyncStore` now runs a sync-only backend on the context's thread pool, and batches run concurrently under the context. diff --git a/packages/zarr-storage/changes/PR.feature.md b/packages/zarr-storage/changes/PR.feature.md new file mode 100644 index 0000000000..34b6b37f2b --- /dev/null +++ b/packages/zarr-storage/changes/PR.feature.md @@ -0,0 +1 @@ +Add `zarr-storage`, a new package with a Zarr-agnostic key-value storage API: `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 (`get_if_changed`, `put_if_absent`, `put_if_match`, `delete_if_match`), byte-range reads, reads into caller buffers, and batches (`get_many`, `get_into_many`, `put_many`, `delete_many`). Every store view carries a `Context` holding the resources its operations draw on (a `ThreadPool`, and a `Limiter` per backend resource key, with process-wide defaults), and `store.limited(n)` bounds a burst of operations within the context's limit. The package ships a conformance suite in `zarr_storage.testing` that any backend can run. diff --git a/packages/zarr-storage/src/zarr_storage/__init__.py b/packages/zarr-storage/src/zarr_storage/__init__.py index 0bb50a3f9b..d430790565 100644 --- a/packages/zarr-storage/src/zarr_storage/__init__.py +++ b/packages/zarr-storage/src/zarr_storage/__init__.py @@ -41,7 +41,7 @@ WritableMany, WritableManyAsync, ) -from zarr_storage._resources import Context, Limiter, ThreadPool +from zarr_storage._resources import Context, Limiter, Slot, ThreadPool from zarr_storage._store import AsyncStore, Store from zarr_storage._types import ( ByteRange, @@ -104,6 +104,7 @@ "ReadableMany", "ReadableManyAsync", "Rejected", + "Slot", "StorageError", "Store", "StoreClosedError", diff --git a/packages/zarr-storage/src/zarr_storage/_protocols.py b/packages/zarr-storage/src/zarr_storage/_protocols.py index dd06555970..9ee4d03c56 100644 --- a/packages/zarr-storage/src/zarr_storage/_protocols.py +++ b/packages/zarr-storage/src/zarr_storage/_protocols.py @@ -118,6 +118,8 @@ async def aclose(self) -> None: 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.""" ... @@ -155,6 +157,8 @@ def get_into(self, path: str, out: O_contra, byte_range: ByteRange | None) -> Co class Writable(Backend, Protocol): + """Writes and deletes values.""" + def put(self, path: str, value: memoryview) -> Written: """Write `value` at `path`.""" ... @@ -173,6 +177,8 @@ def delete_dir(self, directory: str) -> None: 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: @@ -181,6 +187,8 @@ def put_if_match( 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`.""" ... @@ -188,6 +196,9 @@ def delete_if_match(self, path: str, generation: Generation) -> Deleted | Reject @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]]: @@ -197,6 +208,9 @@ def get_many( @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]]: @@ -206,6 +220,9 @@ def get_into_many( @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]]: @@ -220,6 +237,8 @@ def delete_many( 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.""" ... @@ -231,6 +250,8 @@ def list_dir(self, directory: str) -> Iterator[ListItem]: @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( @@ -246,6 +267,8 @@ 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: ... @@ -253,6 +276,8 @@ async def get_into_async( @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: ... @@ -264,6 +289,8 @@ 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: ... @@ -271,6 +298,8 @@ async def put_if_match_async( @runtime_checkable class DeletableIfMatchAsync(Backend, Protocol): + """`DeletableIfMatch`, as a coroutine.""" + async def delete_if_match_async( self, path: str, generation: Generation ) -> Deleted | Rejected | Missing: ... @@ -278,6 +307,8 @@ async def delete_if_match_async( @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]]: ... @@ -285,6 +316,8 @@ def get_many_async( @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]]: ... @@ -292,6 +325,8 @@ def get_into_many_async( @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]]: ... @@ -303,6 +338,8 @@ def delete_many_async( @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/_store.py b/packages/zarr-storage/src/zarr_storage/_store.py index 8ae7e1b462..87c9b7b150 100644 --- a/packages/zarr-storage/src/zarr_storage/_store.py +++ b/packages/zarr-storage/src/zarr_storage/_store.py @@ -167,11 +167,11 @@ def limited(self, limit: int) -> Self: """ return self.with_context(self._context.limited(self._backend.resource_key, limit)) - def shares_backend(self, other: _View[Backend]) -> bool: + def shares_backend(self, other: Store[Backend] | AsyncStore[Backend]) -> bool: """Whether `other` reads and writes through the same backend object.""" return self._backend is other._backend - def overlaps(self, other: _View[Backend]) -> bool: + def overlaps(self, other: Store[Backend] | AsyncStore[Backend]) -> bool: """Whether a key could be visible through both stores: same backend, nested roots.""" return self.shares_backend(other) and ( is_within(self._root, other._root) or is_within(other._root, self._root) diff --git a/packages/zarr-storage/tests/test_batch.py b/packages/zarr-storage/tests/test_batch.py index 46e6e8fce4..d847cec679 100644 --- a/packages/zarr-storage/tests/test_batch.py +++ b/packages/zarr-storage/tests/test_batch.py @@ -127,7 +127,13 @@ def test_runner_on_a_pool_gives_back_every_slot(fails: int | None) -> None: finally: pool.shutdown() assert limiter.in_use == 0 - assert tracker.started == ({0} if fails == 0 else set(range(8))) + if fails is None: + assert tracker.started == set(range(8)) + else: + # The pool's thread may take the next queued operation before the runner sees the failure; + # nothing past the first window starts. + assert 0 in tracker.started + assert tracker.started <= set(range(4)) def test_batch_error_keeps_its_report_when_split() -> None: diff --git a/packages/zarr-storage/tests/test_resources.py b/packages/zarr-storage/tests/test_resources.py index 5099866a82..c17178636a 100644 --- a/packages/zarr-storage/tests/test_resources.py +++ b/packages/zarr-storage/tests/test_resources.py @@ -546,7 +546,7 @@ def test_narrowly_limited_burst_leaves_the_pool_to_others(tmp_path: Path) -> Non waited = asyncio.run(_burst_and_probe(slow.limited(1), other)) finally: pool.shutdown() - assert waited < 0.15 + assert waited < 0.5 # parked threads would make it wait for the whole burst, about 1.2 s async def _cancel_write_waiting_for_its_slot(store: AsyncStore[LocalBackend]) -> None: From 10436e70d7f90db2f9ccbeec58010f6b55b2d82f Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 20:33:44 +0100 Subject: [PATCH 17/31] docs(zarr-storage): name the changelog fragment 0000 until the upstream PR is numbered Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/changes/{PR.feature.md => 0000.feature.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename packages/zarr-storage/changes/{PR.feature.md => 0000.feature.md} (100%) diff --git a/packages/zarr-storage/changes/PR.feature.md b/packages/zarr-storage/changes/0000.feature.md similarity index 100% rename from packages/zarr-storage/changes/PR.feature.md rename to packages/zarr-storage/changes/0000.feature.md From 17d525c6bc3c5d9e382fb835fbc58460b096f883 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 20:40:27 +0100 Subject: [PATCH 18/31] fix(zarr-storage): take slots on pool threads again, and skip operations cancelled before theirs 2ff082e96 moved slot acquisition before work went to the pool. That removed one stall but created a deadlock: once a pool thread itself needs a slot (a sync `Store` used on a pool thread, or a backend that delegates to a `Store`), every thread can wait for a slot held by work queued behind them. This restores the original rule, so no operation holds a slot while it waits for a thread, and keeps the fixes that don't depend on it: - an `AsyncStore` operation of a sync backend whose task is cancelled before it takes its slot is skipped, so a cancelled write no longer lands long after its caller moved on; - `ThreadPool.run` runs inline on the pool's own threads; - a `Store` batch cancels its queued operations after the first failure; - a thread interrupted while waiting for a slot gives it back; - a pickled derived view stays derived. The stall a `limited(1)` burst can cause on a shared pool is listed under "Open" in DESIGN.md. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/DESIGN.md | 24 +++-- .../zarr-storage/src/zarr_storage/_batch.py | 70 +++---------- .../src/zarr_storage/_resources.py | 34 ++----- .../zarr-storage/src/zarr_storage/_store.py | 53 ++++++---- packages/zarr-storage/tests/test_batch.py | 29 +----- packages/zarr-storage/tests/test_resources.py | 99 +++++-------------- 6 files changed, 96 insertions(+), 213 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 0dccaa64df..752083ec25 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -256,14 +256,14 @@ object-store requests by wrapping the store in object_store's `LimitStore` and s 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 **before work goes to the pool**: an `AsyncStore` takes the slot in its task, a `Store` batch - on its calling thread, and the pool thread gives it back when the work finishes. Pool threads - never wait for slots, so a narrowly limited burst occupies one thread per slot, never the whole - pool, and slot holders waiting for threads always get one. (An earlier draft took slots on the - pool threads; a `limited(1)` burst then parked every thread of the shared pool.) -- **Cancellation**: an operation cancelled while it waits for its slot or for a thread never runs; - one cancelled while running on a thread finishes before the cancellation propagates. So once a - cancelled call returns, it has no further effect. + 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. 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 @@ -362,11 +362,15 @@ resources are passed in a store's context. - 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. - Listings hold no slot of the context's limiter. +- 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- and normalization-insensitive filesystems (APFS, NTFS) store distinct keys such as `a` and - `A` in one file, under `LocalBackend` and obstore's `LocalStore` alike. +- 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 diff --git a/packages/zarr-storage/src/zarr_storage/_batch.py b/packages/zarr-storage/src/zarr_storage/_batch.py index 70e53ccb7d..3906043056 100644 --- a/packages/zarr-storage/src/zarr_storage/_batch.py +++ b/packages/zarr-storage/src/zarr_storage/_batch.py @@ -2,14 +2,8 @@ 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`. - -`run_many` holds a slot of its `limiter` for each operation. It takes the slot on the calling -thread before the operation goes to the pool, and the pool thread gives it back when the operation -finishes, so pool threads never wait for slots: a narrowly limited batch can't park the threads -every other user of the pool needs. +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 @@ -22,7 +16,7 @@ from collections.abc import AsyncIterator, Callable, Coroutine, Iterator, Sequence from concurrent.futures import Future - from zarr_storage._resources import Limiter, Slot, ThreadPool + from zarr_storage._resources import ThreadPool __all__ = ["run_many", "run_many_async"] @@ -37,47 +31,23 @@ def run_many( requests: Sequence[tuple[*Ts]], pool: ThreadPool | None = None, window: int = 1, - limiter: Limiter | None = None, ) -> Iterator[tuple[int, R]]: - """Call `fn(*request)` for each request: one at a time, or on `pool`, `window` at once, each - holding a slot of `limiter` if one is given. + """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, limiter) - return _run_on(pool, fn, requests, window, limiter) - - -def _take(limiter: Limiter | None) -> Slot | None: - """A slot of `limiter`, entered on the calling thread; `None` without a limiter.""" - if limiter is None: - return None - slot = limiter.slot() - slot.__enter__() - return slot - - -def _give_back(slot: Slot | None) -> None: - if slot is not None: - slot.__exit__(None, None, None) - - -def _holding(slot: Slot | None, fn: Callable[[Unpack[Ts]], R], *args: *Ts) -> R: - """`fn(*args)`, then give back `slot`, which the submitting thread took.""" - try: - return fn(*args) - finally: - _give_back(slot) + return _run_serially(fn, requests) + return _run_on(pool, fn, requests, window) def _run_serially( - fn: Callable[[Unpack[Ts]], R], requests: Sequence[tuple[*Ts]], limiter: Limiter | None + fn: Callable[[Unpack[Ts]], R], requests: Sequence[tuple[*Ts]] ) -> Iterator[tuple[int, R]]: for index, request in enumerate(requests): try: - result = _holding(_take(limiter), fn, *request) + 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 @@ -88,25 +58,18 @@ def _run_on( fn: Callable[[Unpack[Ts]], R], requests: Sequence[tuple[*Ts]], window: int, - limiter: Limiter | None, ) -> Iterator[tuple[int, R]]: - pending: dict[Future[R], tuple[int, Slot | None]] = {} + 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: - slot = _take(limiter) - try: - future = pool.submit(_holding, slot, fn, *requests[started]) - except BaseException: - _give_back(slot) - raise - pending[future] = (started, slot) + pending[pool.submit(fn, *requests[started])] = started started += 1 done, _ = wait(pending, return_when=FIRST_COMPLETED) for future in done: - index, _slot = pending.pop(future) + index = pending.pop(future) error = future.exception() if error is None: yield index, future.result() @@ -122,13 +85,10 @@ def _run_on( raise ExceptionGroup(_MESSAGE, errors) -def _cancel_queued(pending: dict[Future[R], tuple[int, Slot | None]]) -> None: - """Cancel the operations in `pending` that haven't started, giving back their slots; those - running stay, and give back their own.""" - for future, (_index, slot) in list(pending.items()): - if future.cancel(): - del pending[future] - _give_back(slot) +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( diff --git a/packages/zarr-storage/src/zarr_storage/_resources.py b/packages/zarr-storage/src/zarr_storage/_resources.py index ffdfd9d2b3..85b010aa9e 100644 --- a/packages/zarr-storage/src/zarr_storage/_resources.py +++ b/packages/zarr-storage/src/zarr_storage/_resources.py @@ -23,6 +23,7 @@ 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 @@ -129,21 +130,16 @@ def submit(self, fn: Callable[[*Ts], R], /, *args: *Ts) -> Future[R]: async def run(self, fn: Callable[[*Ts], R], /, *args: *Ts) -> R: """Await `fn(*args)`, run on one of the pool's threads. - If the awaiting task is cancelled, work that has not started never runs, and work that has - started finishes before the cancellation propagates: once a cancelled `run` returns, the - work has no further effect. 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. + 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) - future = self.submit(fn, *args) - try: - return await asyncio.wrap_future(future) - except asyncio.CancelledError: - if not future.cancel(): - await _finish(future) - raise + 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. @@ -157,20 +153,6 @@ def shutdown(self, *, wait: bool = True) -> None: executor.shutdown(wait=wait) -async def _finish(future: Future[R]) -> None: - """Wait until `future`, already running, is done, through any further cancellation.""" - inner = asyncio.wrap_future(future) - while not inner.done(): - try: - await asyncio.shield(inner) - except asyncio.CancelledError: - continue - except BaseException: # noqa: BLE001 -- the work's own failure; the cancellation propagates - break - if not inner.cancelled(): - inner.exception() # retrieved, so it is not reported as never retrieved - - class _DefaultThreadPool(ThreadPool): """The process-wide pool: never shut down, and unpickled as the receiver's own default.""" diff --git a/packages/zarr-storage/src/zarr_storage/_store.py b/packages/zarr-storage/src/zarr_storage/_store.py index 87c9b7b150..5c9f0f73e1 100644 --- a/packages/zarr-storage/src/zarr_storage/_store.py +++ b/packages/zarr-storage/src/zarr_storage/_store.py @@ -6,14 +6,16 @@ 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 by whoever hands work to the pool, before handing it over, and given back when the -work finishes: an `AsyncStore` takes it in its task, and a `Store` batch on its calling thread. Pool -threads never wait for slots, so a narrowly limited burst can't park the threads every other user -of the pool needs, and a cancelled operation that was still waiting for its slot never runs. +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 @@ -80,6 +82,20 @@ """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)) @@ -344,11 +360,8 @@ def __exit__( 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, each - holding a slot of the limiter.""" - return run_many( - fn, requests, self._context.threads, self._limiter.limit, limiter=self._limiter - ) + """`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]] @@ -521,7 +534,7 @@ def get_many( backend = self._backend if isinstance(backend, ReadableMany): return self._streamed(batch, backend.get_many(paths, self._context)) - return self._streamed(batch, self._run_many(backend.get, paths)) + return self._streamed(batch, self._run_many(self._get, paths)) def get_into_many( self: Store[ReadableInto[O]], @@ -538,7 +551,7 @@ def get_into_many( 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(backend.get_into, paths)) + return self._streamed(batch, self._run_many(self._get_into, paths)) def put_many( self: Store[Writable], items: Iterable[tuple[str, Buffer]] @@ -554,7 +567,7 @@ def put_many( backend = self._backend if isinstance(backend, WritableMany): return self._finished(keys, backend.put_many(requests, self._context)) - return self._finished(keys, self._run_many(backend.put, requests)) + return self._finished(keys, self._run_many(self._put, requests)) def delete_many( self: Store[Writable], keys: Iterable[str] @@ -565,7 +578,7 @@ def delete_many( backend = self._backend if isinstance(backend, WritableMany): return self._finished(batch, backend.delete_many(paths, self._context)) - return self._finished(batch, self._run_many(backend.delete, [(path,) for path in paths])) + return self._finished(batch, self._run_many(self._delete, [(path,) for path in paths])) # ----------------------------------------------------------------- listing @@ -665,14 +678,16 @@ async def __aexit__( # ----------------------------------------------------------------- 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 here, before the work goes to - the pool. + """`fn(*args)` on the context's pool, holding a slot taken on the pool thread. - If the task is cancelled while it waits for the slot or for a thread, `fn` never runs; once - `fn` is running, the cancellation waits for it to finish, so the slot covers it throughout. + If the task is cancelled before the operation takes its slot, the operation never runs. """ - async with self._slot(): - return await self._context.threads.run(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]] diff --git a/packages/zarr-storage/tests/test_batch.py b/packages/zarr-storage/tests/test_batch.py index d847cec679..696b15a6df 100644 --- a/packages/zarr-storage/tests/test_batch.py +++ b/packages/zarr-storage/tests/test_batch.py @@ -11,7 +11,7 @@ from zarr_storage import BatchError from zarr_storage._batch import run_many, run_many_async -from zarr_storage._resources import Limiter, ThreadPool +from zarr_storage._resources import ThreadPool if TYPE_CHECKING: from collections.abc import AsyncIterator @@ -109,33 +109,6 @@ def test_runner_stops_starting_after_a_failure(mode: str, window: int) -> None: assert sorted(results) == [(x, x * x) for x in sorted(tracker.started - {0})] -@pytest.mark.parametrize("fails", [None, 0]) -def test_runner_on_a_pool_gives_back_every_slot(fails: int | None) -> None: - """Slots are taken before work is queued on the pool; work cancelled after a failure, and work - that ran, give theirs back.""" - tracker = _Tracker(fails=fails) - limiter = Limiter(4) - pool = ThreadPool(1) - requests = [(x,) for x in range(8)] - results: list[tuple[int, int]] = [] - try: - if fails is None: - results.extend(run_many(tracker, requests, pool, 4, limiter=limiter)) - else: - with pytest.raises(ExceptionGroup): - results.extend(run_many(tracker, requests, pool, 4, limiter=limiter)) - finally: - pool.shutdown() - assert limiter.in_use == 0 - if fails is None: - assert tracker.started == set(range(8)) - else: - # The pool's thread may take the next queued operation before the runner sees the failure; - # nothing past the first window starts. - assert 0 in tracker.started - assert tracker.started <= set(range(4)) - - 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",)) diff --git a/packages/zarr-storage/tests/test_resources.py b/packages/zarr-storage/tests/test_resources.py index c17178636a..e8ad4f1f0c 100644 --- a/packages/zarr-storage/tests/test_resources.py +++ b/packages/zarr-storage/tests/test_resources.py @@ -251,51 +251,6 @@ def test_thread_pool_of_a_bad_size_raises(size: object, error: type[Exception]) ThreadPool(size) # pyright: ignore[reportArgumentType] -def _wait_then_record(gate: threading.Event, ran: list[str], name: str) -> None: - gate.wait() - ran.append(name) - - -async def _cancel_runs(pool: ThreadPool) -> tuple[list[str], list[str]]: - """Cancel one `run` whose work hasn't started and one whose work is running; return what ran - by the time each cancellation finished.""" - ran: list[str] = [] - busy, started = threading.Event(), threading.Event() - pool.submit(busy.wait) # holds the only thread, so the next run is queued - queued = asyncio.ensure_future(pool.run(ran.append, "queued")) - await asyncio.sleep(0.05) - queued.cancel() - with pytest.raises(asyncio.CancelledError): - await queued - busy.set() - gate = threading.Event() - running = asyncio.ensure_future(pool.run(_started_then, started, gate, ran)) - await asyncio.to_thread(started.wait) - running.cancel() - threading.Timer(0.05, gate.set).start() - with pytest.raises(asyncio.CancelledError): - await running - after_running = list(ran) - await asyncio.sleep(0.05) - return after_running, ran - - -def _started_then(started: threading.Event, gate: threading.Event, ran: list[str]) -> None: - started.set() - _wait_then_record(gate, ran, "running") - - -def test_cancelled_run_never_starts_queued_work_and_waits_for_running_work() -> None: - """Once a cancelled `run` returns, its work has either not run at all or already finished.""" - pool = ThreadPool(1) - try: - after_running, finally_ran = asyncio.run(_cancel_runs(pool)) - finally: - pool.shutdown() - assert after_running == ["running"] - assert finally_ran == ["running"] - - def _run_on_own_thread(pool: ThreadPool) -> bool: return asyncio.run(pool.run(pool.in_worker)) @@ -486,13 +441,12 @@ def _settle() -> None: time.sleep(0.05) -def test_sync_batch_and_async_read_sharing_one_thread_and_one_slot_both_finish( +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. Neither may wait forever for the other: slots are taken - before work goes to the pool, so the batch's read holds the slot while it waits for the thread, - and the async read waits for the slot without holding the thread.""" + 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") @@ -515,38 +469,33 @@ def test_sync_batch_and_async_read_sharing_one_thread_and_one_slot_both_finish( assert limiter.in_use == 0 -class _SlowLocalBackend(LocalBackend): - def get(self, path: str, byte_range: ByteRange | None) -> Found | Missing: - time.sleep(0.2) - return super().get(path, byte_range) +def _sync_get(store: Store[LocalBackend]) -> object: + return store.get("k") -async def _burst_and_probe( - burst: AsyncStore[LocalBackend], other: AsyncStore[LocalBackend] -) -> float: - reads = [asyncio.ensure_future(burst.get("k")) for _ in range(6)] - await asyncio.sleep(0.05) # the burst is under way - start = time.monotonic() - assert isinstance(await other.get("k"), Found) - waited = time.monotonic() - start - await asyncio.gather(*reads) - return waited +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_narrowly_limited_burst_leaves_the_pool_to_others(tmp_path: Path) -> None: - """Six slow reads through a `limited(1)` view of a sync backend occupy one pool thread, not - all of them, so another store on the same pool isn't queued behind the burst.""" - pool = ThreadPool(2) - context = Context(threads=pool) - slow = AsyncStore(_SlowLocalBackend(tmp_path / "slow"), context=context) - other = AsyncStore(LocalBackend(tmp_path / "other"), context=context) +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: - slow.as_sync().put("k", b"x") - other.as_sync().put("k", b"x") - waited = asyncio.run(_burst_and_probe(slow.limited(1), other)) + assert _finishes( + lambda: results.extend(asyncio.run(_sync_op_on_the_pool_beside_an_async_op(store))) + ) finally: - pool.shutdown() - assert waited < 0.5 # parked threads would make it wait for the whole burst, about 1.2 s + 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: From d85f5a97ccca10a4f304792ac37de6b97650fc6d Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 20:44:38 +0100 Subject: [PATCH 19/31] fix(zarr-storage): walk delete_dir by file descriptor so a swapped symlink is never followed `delete_dir` checked for symlinks by path, then walked by path, so whoever could write the root could swap a directory for a symlink between the check and the walk and have files outside the root deleted (the classic rmtree race). Where the platform has `dir_fd` (not Windows), `delete_dir` now opens each directory relative to its parent with `O_NOFOLLOW`, locks it through that descriptor, and unlinks a name that turned into a link instead of following it, as `shutil.rmtree` does. On Windows the path walk skips directory junctions, which `is_symlink` doesn't report. Also: backend paths are checked against the key grammar, so an absolute path or `..` passed to the public backend can't leave the root; a FIFO or device in a key's place reads as absent instead of blocking `get`; a write under any non-directory name raises `KeyConflictError` at once; and the docs quickstart runs as written. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/DESIGN.md | 17 +- packages/zarr-storage/docs/index.md | 23 +- .../src/zarr_storage/backends/_local.py | 203 ++++++++++++++++-- packages/zarr-storage/tests/test_local.py | 56 ++++- 4 files changed, 265 insertions(+), 34 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 752083ec25..5505d9200c 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -195,11 +195,15 @@ goes. Deletes, and writes whose precondition fails, can leave directories behind 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, since -what lies beyond one may lie outside the root: listings leave such a link out, return nothing for a -directory reached through one, and `delete_dir` deletes nothing through one. Single-key operations -go through it, as the filesystem resolves the path. Dangling symlinks and special files are not -keys. Each write stamps its file with a nanosecond mtime unique within the process, because +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`. @@ -360,7 +364,8 @@ resources are passed in a store's context. - 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. +- 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 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 diff --git a/packages/zarr-storage/docs/index.md b/packages/zarr-storage/docs/index.md index 25db68c637..9663e4d99c 100644 --- a/packages/zarr-storage/docs/index.md +++ b/packages/zarr-storage/docs/index.md @@ -31,16 +31,16 @@ types, one per outcome, so a `match` handles each: from zarr_storage import Found, Missing, Store from zarr_storage.backends import MemoryBackend -with Store(MemoryBackend()) as store: - 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'] +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 @@ -61,6 +61,9 @@ 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. diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index ddbdae1c85..cb24c17bb5 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -21,6 +21,7 @@ KeyConflictError, UnsupportedOperationError, ) +from zarr_storage._keys import check_key from zarr_storage._types import ( Copied, Deleted, @@ -68,6 +69,26 @@ ) _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") @@ -81,6 +102,8 @@ 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. @@ -168,9 +191,13 @@ def _key_errors(path: str) -> Generator[None, None, None]: def _open_key(file: Path) -> BufferedReader | None: - """The file at `file` opened for reading, or `None` if it is absent or is a directory.""" + """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: - return open(file, "rb") + fd = os.open(file, os.O_RDONLY | _NONBLOCK | getattr(os, "O_BINARY", 0)) except (FileNotFoundError, IsADirectoryError, NotADirectoryError): return None except PermissionError: @@ -178,6 +205,17 @@ def _open_key(file: Path) -> BufferedReader | None: 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: @@ -206,7 +244,7 @@ def _stat_key(file: Path) -> os.stat_result | None: @contextlib.contextmanager -def _directory_lock(directory: Path) -> Generator[None, None, None]: +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 @@ -216,12 +254,14 @@ def _directory_lock(directory: Path) -> Generator[None, None, None]: 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 + 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) + 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 @@ -233,7 +273,7 @@ def _directory_lock(directory: Path) -> Generator[None, None, None]: _lock(fd) held = os.fstat(fd) try: - current = os.stat(lock_path) + 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) == ( @@ -330,9 +370,68 @@ def _reclaim(directory: Path) -> bool: 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 @@ -343,12 +442,17 @@ def _remove_tree(directory: Path, *, remove_self: bool) -> None: with os.scandir(directory) as entries: children = [e for e in entries if e.name != _LOCK_NAME] for entry in children: - if entry.name.endswith(RESERVED_SUFFIX): + 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: @@ -453,12 +557,17 @@ def close(self) -> None: # --- 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 @@ -619,11 +728,13 @@ def _stage(self, value: memoryview) -> tuple[Path, Generation]: return temp, staged def _has_key_parent(self, file: Path) -> bool: - """Whether a directory between the root and `file` is a regular file (a key), or a - dangling symlink, which no write can turn into a directory.""" + """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: - if _stat_key(parent) is not None or (parent.is_symlink() and not parent.exists()): + if (parent.exists() and not parent.is_dir()) or ( + _is_link(parent) and not parent.exists() + ): return True parent = parent.parent return False @@ -645,8 +756,8 @@ def _commit( except (FileExistsError, NotADirectoryError) as e: if self._has_key_parent(file): raise KeyConflictError( - f"A parent of {path!r} is a key (or a dangling symlink), so it can't also be " - "a directory." + 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. @@ -688,19 +799,48 @@ def _delete( def delete_dir(self, directory: str) -> None: target = self._directory(directory) with _key_errors(directory): - if target == self._root: + 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: - if target.is_symlink(): + while target != self._root and target != target.parent: + if _is_link(target): return True target = target.parent return False @@ -733,7 +873,7 @@ def _walk(directory: Path, prefix: str) -> Iterator[str]: except (FileNotFoundError, NotADirectoryError): return for entry in entries: - if _is_reserved(entry.name): + 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}/") @@ -743,7 +883,7 @@ def _walk(directory: Path, prefix: str) -> Iterator[str]: def _classify(entries: list[os.DirEntry[str]]) -> Iterator[ListItem]: for entry in entries: - if _is_reserved(entry.name): + if _is_reserved(entry.name) or _is_junction_entry(entry): continue if entry.is_dir(follow_symlinks=False): yield Prefix(entry.name) @@ -751,6 +891,35 @@ def _classify(entries: list[os.DirEntry[str]]) -> Iterator[ListItem]: 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). diff --git a/packages/zarr-storage/tests/test_local.py b/packages/zarr-storage/tests/test_local.py index 5eed4232c6..4a66539fcd 100644 --- a/packages/zarr-storage/tests/test_local.py +++ b/packages/zarr-storage/tests/test_local.py @@ -3,8 +3,10 @@ import errno import multiprocessing import os +import shutil import threading import time +from functools import partial from typing import TYPE_CHECKING import pytest @@ -15,13 +17,14 @@ InvalidKeyError, Key, KeyConflictError, + Missing, Prefix, Rejected, Store, UnsupportedOperationError, Written, ) -from zarr_storage.backends import LocalBackend +from zarr_storage.backends import LocalBackend, _local from zarr_storage.backends._local import RESERVED_SUFFIX, _directory_lock, segment_problem from zarr_storage.testing import ( ConditionalDeleteSuite, @@ -352,6 +355,57 @@ def test_symlinked_directory_is_outside_the_tree_listings_and_delete_dir_walk( 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(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") + + +@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(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(tmp_path / "root")) From abd57b8bb4679b39f972cc7156100f74c2bff84b Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 20:58:30 +0100 Subject: [PATCH 20/31] fix(zarr-storage): wait for slots as a task on pool-thread loops; check a write's parents with one stat Two regressions from the previous fixes, found in review: - `ThreadPool.run` runs inline on the pool's own threads, and the inline call took its slot with a blocking acquire. On an event loop running inside the pool's work, that blocked the loop's thread while another task on the same loop held the slot across an await, so neither could proceed. On those threads `AsyncStore` now takes the slot with `async with` and runs the operation inline. - `_has_key_parent` asked `exists()` and then `is_dir()`, so a concurrent `delete_dir` between the two made a retryable write raise `KeyConflictError`. It now decides from one `stat`. DESIGN.md also states the cancellation rule precisely and lists two known limits: descriptor use per directory level in `delete_dir`, and a derived view pickled without its owner. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/DESIGN.md | 8 ++- .../zarr-storage/src/zarr_storage/_store.py | 8 ++- .../src/zarr_storage/backends/_local.py | 14 +++-- packages/zarr-storage/tests/test_local.py | 9 +++ packages/zarr-storage/tests/test_resources.py | 63 ++++++++++++++++++- 5 files changed, 93 insertions(+), 9 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 5505d9200c..234f7f0852 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -266,8 +266,8 @@ object-store requests by wrapping the store in object_store's `LimitStore` and s 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. One already running finishes on its thread, as with - `run_in_executor`. + 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 @@ -367,6 +367,10 @@ resources are passed in a store's context. - 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. +- `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 diff --git a/packages/zarr-storage/src/zarr_storage/_store.py b/packages/zarr-storage/src/zarr_storage/_store.py index 5c9f0f73e1..1f32dafc2f 100644 --- a/packages/zarr-storage/src/zarr_storage/_store.py +++ b/packages/zarr-storage/src/zarr_storage/_store.py @@ -680,8 +680,14 @@ async def __aexit__( 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 task is cancelled before the operation takes its slot, the operation never runs. + 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) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index cb24c17bb5..927bec8c69 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -732,10 +732,16 @@ def _has_key_parent(self, file: Path) -> bool: directory: a key, a special file, or a dangling symlink.""" parent = file.parent while parent != self._root: - if (parent.exists() and not parent.is_dir()) or ( - _is_link(parent) and not parent.exists() - ): - return True + 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 + else: + if not stat.S_ISDIR(st.st_mode): + return True parent = parent.parent return False diff --git a/packages/zarr-storage/tests/test_local.py b/packages/zarr-storage/tests/test_local.py index 4a66539fcd..1bdfe34a4c 100644 --- a/packages/zarr-storage/tests/test_local.py +++ b/packages/zarr-storage/tests/test_local.py @@ -396,6 +396,15 @@ def test_fifo_is_not_a_key(tmp_path: Path) -> None: 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.""" diff --git a/packages/zarr-storage/tests/test_resources.py b/packages/zarr-storage/tests/test_resources.py index e8ad4f1f0c..4c9754a4c5 100644 --- a/packages/zarr-storage/tests/test_resources.py +++ b/packages/zarr-storage/tests/test_resources.py @@ -12,12 +12,24 @@ import pytest from obstore.store import MemoryStore -from zarr_storage import AsyncStore, Context, Found, Limiter, Missing, Store, ThreadPool +from zarr_storage import ( + AsyncStore, + Context, + Found, + FoundRanges, + Generation, + Limiter, + Missing, + ObjectMetadata, + Store, + ThreadPool, + Unchanged, +) from zarr_storage._resources import _ThreadWaiter, default_limiter from zarr_storage.backends import LocalBackend, MemoryBackend, ObjectStoreBackend if TYPE_CHECKING: - from collections.abc import Callable + from collections.abc import Callable, Sequence from pathlib import Path from zarr_storage import ByteRange @@ -516,3 +528,50 @@ def test_cancelled_write_of_a_sync_backend_never_lands(tmp_path: Path) -> None: 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"] From 79be01e8046492ed24f8fba098dc552412b0cceb Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 21:01:21 +0100 Subject: [PATCH 21/31] fix(zarr-storage): report a symlink loop above a key as a key conflict `_has_key_parent` let `ELOOP` from its `stat` escape, where it used to raise `KeyConflictError` for a symlink loop in a key's parent. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/src/zarr_storage/backends/_local.py | 4 ++++ packages/zarr-storage/tests/test_local.py | 7 +++++++ 2 files changed, 11 insertions(+) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index 927bec8c69..ddeb3f541c 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -739,6 +739,10 @@ def _has_key_parent(self, file: Path) -> bool: 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 diff --git a/packages/zarr-storage/tests/test_local.py b/packages/zarr-storage/tests/test_local.py index 1bdfe34a4c..76550bc262 100644 --- a/packages/zarr-storage/tests/test_local.py +++ b/packages/zarr-storage/tests/test_local.py @@ -432,6 +432,13 @@ def test_dangling_symlink_is_not_a_key(tmp_path: Path) -> None: assert (list(store.list()), store.exists("link")) == ([], False) +def test_put_under_a_symlink_loop_raises(tmp_path: Path) -> None: + store = Store(LocalBackend(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(tmp_path / "root")) (tmp_path / "root" / "link").symlink_to(tmp_path / "nowhere") From 317b72d379991d8c4e629869a195eef151e329a9 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 21:08:30 +0100 Subject: [PATCH 22/31] 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/{0000.feature.md => 488.feature.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename packages/zarr-storage/changes/{0000.feature.md => 488.feature.md} (100%) diff --git a/packages/zarr-storage/changes/0000.feature.md b/packages/zarr-storage/changes/488.feature.md similarity index 100% rename from packages/zarr-storage/changes/0000.feature.md rename to packages/zarr-storage/changes/488.feature.md From 5f31fea39545815dc8ef50309263b52c983a7447 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 21:19:15 +0100 Subject: [PATCH 23/31] feat(zarr-storage)!: make LocalBackend.create the only constructor that changes the disk `LocalBackend(root, create=True)` let a keyword decide whether constructing a backend made directories. `LocalBackend(root)` now reads the filesystem and changes nothing, raising `FileNotFoundError` for a missing root and `NotADirectoryError` for a file; `LocalBackend.create(root)` makes the directory and any missing parents first. The `create` keyword is gone. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/DESIGN.md | 6 +- .../src/zarr_storage/backends/_local.py | 58 +++++++++++++------ packages/zarr-storage/tests/test_local.py | 51 +++++++++++----- packages/zarr-storage/tests/test_resources.py | 6 +- 4 files changed, 83 insertions(+), 38 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 234f7f0852..a78a745a6d 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -208,6 +208,8 @@ filesystems such as ext4 reuse inodes at once and advance mtimes only per clock 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); @@ -358,7 +360,9 @@ the meaning alone (limits, caching, retries) are context resources. ## Configuration No global configuration. Every knob is a constructor parameter with its default in the signature; -resources are passed in a store's context. +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 diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index ddeb3f541c..b378e84649 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -12,7 +12,7 @@ import time import uuid from pathlib import Path -from typing import TYPE_CHECKING, TypedDict, TypeVar +from typing import TYPE_CHECKING, Self, TypedDict, TypeVar from zarr_storage._buffers import byte_view from zarr_storage._byte_range import resolve @@ -490,35 +490,57 @@ class LocalBackend: 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 or Unicode-normalizing filesystems (the - defaults on macOS and Windows), keys that differ only in case or normalization are the same key. + 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. - create - Create `root` if it doesn't exist. With `create=False`, a missing root raises - `FileNotFoundError`. + + Raises + ------ + FileNotFoundError + If `root` doesn't exist. + NotADirectoryError + If `root` is a file. """ - def __init__( - self, - root: str | os.PathLike[str], - *, - create: bool = True, - ) -> None: + def __init__(self, root: str | os.PathLike[str]) -> None: self._root = Path(root).resolve() - if self._root.exists() and not self._root.is_dir(): - raise NotADirectoryError(f"The root {str(self._root)!r} is a file, not a directory.") - if create: - self._root.mkdir(parents=True, exist_ok=True) - elif not self._root.is_dir(): - raise FileNotFoundError(f"The root directory {str(self._root)!r} does not exist.") + 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) + try: + path.mkdir(parents=True, exist_ok=True) + except FileExistsError: + raise NotADirectoryError( + f"The root {str(path.resolve())!r} is a file, not a directory." + ) from None + return cls(path) + @property def root(self) -> Path: """The directory that holds the keys.""" diff --git a/packages/zarr-storage/tests/test_local.py b/packages/zarr-storage/tests/test_local.py index 76550bc262..53f2bbf5bd 100644 --- a/packages/zarr-storage/tests/test_local.py +++ b/packages/zarr-storage/tests/test_local.py @@ -109,7 +109,7 @@ def test_delete_dir_of_the_root_keeps_backend_files(tmp_path: Path) -> None: 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(tmp_path / "sub")) + inner = Store(LocalBackend.create(tmp_path / "sub")) outer.delete_dir("sub") inner.put("k", b"x") assert outer.exists("sub/k") @@ -149,16 +149,35 @@ def test_segment_problem(segment: str, windows: bool, problem: str | None) -> No assert problem in found -def test_missing_root_without_create_raises(tmp_path: Path) -> None: - with pytest.raises(FileNotFoundError): - LocalBackend(tmp_path / "missing", create=False) +@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("create", [True, False]) -def test_root_that_is_a_file_raises(tmp_path: Path, create: bool) -> None: +@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"): - LocalBackend(tmp_path / "file", create=create) + make(tmp_path / "file") def test_reserved_key_raises(tmp_path: Path) -> None: @@ -185,7 +204,7 @@ def test_concurrent_creates_through_overlapping_roots( """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(tmp_path / "sub")) if overlapping_roots else outer / "sub" + 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) @@ -346,7 +365,7 @@ def test_symlinked_directory_is_outside_the_tree_listings_and_delete_dir_walk( outside = tmp_path / "outside" (outside / "sub").mkdir(parents=True) (outside / "sub" / "keep").write_bytes(b"x") - store = Store(LocalBackend(tmp_path / "root")) + 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"))) == ([], []) @@ -375,7 +394,7 @@ def test_delete_dir_never_follows_a_directory_swapped_for_a_symlink_mid_walk( outside.mkdir() (outside / "keep").write_bytes(b"x") root = tmp_path / "root" - store = Store(LocalBackend(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) @@ -408,7 +427,7 @@ def test_missing_parent_directory_is_not_a_conflict(tmp_path: Path) -> None: @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(tmp_path / "root") + backend = LocalBackend.create(tmp_path / "root") with pytest.raises(InvalidKeyError): backend.get(path, None) with pytest.raises(InvalidKeyError): @@ -417,7 +436,7 @@ def test_backend_path_outside_the_root_raises(tmp_path: Path, path: str) -> None def test_symlink_to_a_file_is_a_key(tmp_path: Path) -> None: (tmp_path / "target").write_bytes(b"x") - store = Store(LocalBackend(tmp_path / "root")) + 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")] @@ -427,20 +446,20 @@ def test_symlink_to_a_file_is_a_key(tmp_path: Path) -> None: def test_dangling_symlink_is_not_a_key(tmp_path: Path) -> None: - store = Store(LocalBackend(tmp_path / "root")) + 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(tmp_path / "root")) + 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(tmp_path / "root")) + 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") @@ -448,7 +467,7 @@ def test_put_under_a_dangling_symlink_raises(tmp_path: Path) -> None: def test_delete_dir_removes_a_nested_backends_staging(tmp_path: Path) -> None: outer = Store(LocalBackend(tmp_path)) - inner = Store(LocalBackend(tmp_path / "sub")) + inner = Store(LocalBackend.create(tmp_path / "sub")) inner.put("k", b"x") outer.delete_dir("sub") assert not (tmp_path / "sub").exists() diff --git a/packages/zarr-storage/tests/test_resources.py b/packages/zarr-storage/tests/test_resources.py index 4c9754a4c5..ecd11e8c74 100644 --- a/packages/zarr-storage/tests/test_resources.py +++ b/packages/zarr-storage/tests/test_resources.py @@ -332,9 +332,9 @@ def test_pickling_keeps_resources_shared(tmp_path: Path) -> None: wide = Limiter(8) context = Context(threads=ThreadPool(2), limits={"local": Limiter(3, within=wide)}) stores = ( - Store(LocalBackend(tmp_path / "a"), context=context), - Store(LocalBackend(tmp_path / "b"), context=context), - Store(LocalBackend(tmp_path / "c")), + 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 From 28c1c1993e68489ac15d793d3bed22d38c18ab15 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 21:22:05 +0100 Subject: [PATCH 24/31] fix(zarr-storage): never recreate the directories above a LocalBackend's root on write A write made its staging directory with `mkdir(parents=True)`, so a write to a backend whose root's parent was gone (an unmounted volume) rebuilt the whole path on whatever filesystem was there. A write now recreates only the root itself, which an enclosing backend's `delete_dir` can remove, and raises `FileNotFoundError` if the directory above it is gone. `LocalBackend.create` also resolves a relative root once, and names a dangling symlink in the root's place as one. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/DESIGN.md | 5 ++++- .../src/zarr_storage/backends/_local.py | 21 +++++++++++++++---- packages/zarr-storage/tests/test_local.py | 10 +++++++++ 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index a78a745a6d..4d12f0f578 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -209,7 +209,10 @@ 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. +`LocalBackend.create(root)` makes it, and any missing parents, first. A write recreates a root +that has been removed (an enclosing backend's `delete_dir` can remove it), but never the +directories above it, which lie outside the store: a write to a backend on an unmounted volume +raises `FileNotFoundError` instead of rebuilding its path on another filesystem. `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); diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index b378e84649..3567d2e4de 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -532,12 +532,13 @@ def create(cls, root: str | os.PathLike[str]) -> Self: Raises `NotADirectoryError` if `root`, or a parent of it, is a file. """ - path = Path(root) + 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: + what = "a dangling symlink" if path.is_symlink() else "a file" raise NotADirectoryError( - f"The root {str(path.resolve())!r} is a file, not a directory." + f"The root {str(path)!r} is {what}, not a directory." ) from None return cls(path) @@ -718,12 +719,24 @@ def _probe_exact_times(self) -> bool: 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. + Raises `_Retry` if a concurrent delete removed the root or the staging directory, and + `FileNotFoundError` if the root's parent is gone: a write recreates the root (an enclosing + backend's `delete_dir` may remove it), never the directories above it, which lie outside + the store (an unmounted volume must not be rebuilt on another filesystem). """ staging = self._root / _STAGING_NAME temp = staging / uuid.uuid4().hex try: - staging.mkdir(parents=True, exist_ok=True) + self._root.mkdir(exist_ok=True) + except FileNotFoundError: + raise FileNotFoundError( + f"The directory holding the root {str(self._root)!r} no longer exists; a write " + "recreates only the root itself." + ) from None + except FileExistsError: + pass # a file in the root's place; reported below + try: + staging.mkdir(exist_ok=True) with open(temp, "xb") as f: try: f.write(value) diff --git a/packages/zarr-storage/tests/test_local.py b/packages/zarr-storage/tests/test_local.py index 53f2bbf5bd..6626b925a3 100644 --- a/packages/zarr-storage/tests/test_local.py +++ b/packages/zarr-storage/tests/test_local.py @@ -162,6 +162,16 @@ def test_create_makes_a_missing_root_and_keeps_an_existing_one( assert list(store.list()) == (["k"] if existing else []) +def test_put_never_recreates_the_directories_above_the_root(tmp_path: Path) -> None: + """A write recreates a removed root, but not the directories above it, which lie outside the + store (an unmounted volume must not be rebuilt elsewhere).""" + store = Store(LocalBackend.create(tmp_path / "volume" / "root")) + shutil.rmtree(tmp_path / "volume") + with pytest.raises(FileNotFoundError, match="recreates only the root"): + store.put("k", b"x") + assert not (tmp_path / "volume").exists() + + def test_constructing_changes_nothing_on_disk(tmp_path: Path) -> None: before = sorted(p.name for p in tmp_path.iterdir()) LocalBackend(tmp_path) From b4539dde13c6a722f9e6a4cabdeb3200ef8a6915 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 21:29:24 +0100 Subject: [PATCH 25/31] docs(zarr-storage): plan memory-mapped reads and copy-on-write range writes Record the design: a `Mappable` capability whose `map` returns a mapping of one generation (safe because LocalBackend never changes a file in place), kept apart from `get` because mapped bytes do their I/O when touched; and a `WritableRange` capability that patches a copy and renames it into place, cheap where the filesystem clones files. Writes in place would weaken other operations' guarantees, so they'd need a backend type of their own. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/DESIGN.md | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 4d12f0f578..047e1c498c 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -360,6 +360,53 @@ the meaning alone (limits, caching, retries) are context resources. 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; From 20341962881f42e935636e09722df1cb466e7371 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 21:34:33 +0100 Subject: [PATCH 26/31] fix(zarr-storage): recreate a removed LocalBackend root only on the filesystem it was on 28c1c1993 made writes recreate only the root itself, which broke nested backends whose root an enclosing `delete_dir` removed together with a directory above it, and `_probe_exact_times` still rebuilt the whole path. The concern was never depth but filesystems: the backend now records the root's device, and every path that creates directories goes through one check (`_ensure_root`) that recreates the root and missing parents only on that device. A write to a root whose volume was unmounted, whether its path is now missing or an empty mount point, raises `FileNotFoundError`. Key directories are made from the root down, so they never climb above it, and `create`'s error names both cases it can't tell apart. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/DESIGN.md | 11 ++- .../src/zarr_storage/backends/_local.py | 96 ++++++++++++++----- packages/zarr-storage/tests/test_local.py | 36 +++++-- 3 files changed, 108 insertions(+), 35 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 047e1c498c..0c015e1cf1 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -209,10 +209,13 @@ 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. A write recreates a root -that has been removed (an enclosing backend's `delete_dir` can remove it), but never the -directories above it, which lie outside the store: a write to a backend on an unmounted volume -raises `FileNotFoundError` instead of rebuilding its path on another filesystem. +`LocalBackend.create(root)` makes it, and any missing parents, first. A write recreates a root, +and directories above it, that have been removed (an enclosing backend's `delete_dir` can remove +them), but only on the filesystem the root was on when the backend was made: the backend records +the root's device, and a write that would create or land on another device (the root's volume +was unmounted, leaving its path missing or an empty mount point) raises `FileNotFoundError` +instead. Pickling carries the device, so on another machine a write that has to recreate the root +refuses. `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); diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index 3567d2e4de..9b3e18e5b6 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -95,6 +95,7 @@ class _State(TypedDict): root: str + device: int closed: bool @@ -521,6 +522,7 @@ def __init__(self, root: str | os.PathLike[str]) -> None: f"The root directory {str(self._root)!r} does not exist; " "`LocalBackend.create` makes it." ) + self._device = self._root.stat().st_dev self._probe_lock = threading.Lock() self._exact_times: bool | None = None self._closed = False @@ -536,9 +538,9 @@ def create(cls, root: str | os.PathLike[str]) -> Self: try: path.mkdir(parents=True, exist_ok=True) except FileExistsError: - what = "a dangling symlink" if path.is_symlink() else "a file" raise NotADirectoryError( - f"The root {str(path)!r} is {what}, not a directory." + 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) @@ -551,10 +553,11 @@ def __repr__(self) -> str: return f"LocalBackend({str(self._root)!r})" def __getstate__(self) -> _State: - return {"root": str(self._root), "closed": self._closed} + return {"root": str(self._root), "device": self._device, "closed": self._closed} def __setstate__(self, state: _State) -> None: self._root = Path(state["root"]) + self._device = state["device"] self._probe_lock = threading.Lock() self._exact_times = None self._closed = state["closed"] @@ -707,34 +710,79 @@ def _require_exact_times(self) -> None: 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) + for _ in range(_WRITE_ATTEMPTS): + try: + self._ensure_root() + staging.mkdir(exist_ok=True) + with open(probe, "xb") as f: + _set_mtime(f.fileno(), probe, _PROBE_STAMP) + return os.fstat(f.fileno()).st_mtime_ns == _PROBE_STAMP + except _Retry: + continue + except FileNotFoundError as e: + if e.errno != errno.ENOENT: + raise + continue # a concurrent delete_dir removed the staging directory + finally: + probe.unlink(missing_ok=True) + raise OSError("Gave up probing file times: a concurrent delete kept removing the root.") + + def _ensure_root(self) -> None: + """Make the root, and any directories above it, if they are gone, on the filesystem the + root was on when the backend was made, and never on another. + + An enclosing backend's `delete_dir` can remove the root and the directories above it; a + write recreates them. If the nearest directory that exists, or the root itself, is now on + another device (the volume holding the root was unmounted), it raises `FileNotFoundError` + instead of writing there. Raises `KeyConflictError` if a file is in the way, and `_Retry` if + a concurrent delete removed a directory it just made. + """ + missing: list[Path] = [] + path = self._root + while True: + try: + st = os.stat(path) + break + except (FileNotFoundError, NotADirectoryError): + missing.append(path) + path = path.parent + if not stat.S_ISDIR(st.st_mode): + where = "The root" if not missing else f"{str(path)!r}, above the root," + raise KeyConflictError( + f"{where} is now a file (a key of an enclosing store), so the root " + f"{str(self._root)!r} can't be a directory." + ) + if st.st_dev != self._device: + raise FileNotFoundError( + f"{str(path)!r} is not on the filesystem the root {str(self._root)!r} was on (was " + "its volume unmounted?); writes never create directories or files on another " + "filesystem." + ) + for directory in reversed(missing): + try: + directory.mkdir() + except FileExistsError: + pass # a concurrent write made it; a file in its place is found below + except FileNotFoundError as e: + raise _Retry from e + + def _make_key_directories(self, directory: Path) -> None: + """Make `directory` and the directories between the root and it, from the root down, so + nothing above the root is ever made here (that is `_ensure_root`'s job, with its check).""" + depth = len(directory.relative_to(self._root).parts) + for level in reversed([directory, *directory.parents][:depth]): + level.mkdir(exist_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, and - `FileNotFoundError` if the root's parent is gone: a write recreates the root (an enclosing - backend's `delete_dir` may remove it), never the directories above it, which lie outside - the store (an unmounted volume must not be rebuilt on another filesystem). + Raises `_Retry` if a concurrent delete removed the root or the staging directory; see + `_ensure_root` for a root that is gone. """ staging = self._root / _STAGING_NAME temp = staging / uuid.uuid4().hex - try: - self._root.mkdir(exist_ok=True) - except FileNotFoundError: - raise FileNotFoundError( - f"The directory holding the root {str(self._root)!r} no longer exists; a write " - "recreates only the root itself." - ) from None - except FileExistsError: - pass # a file in the root's place; reported below + self._ensure_root() try: staging.mkdir(exist_ok=True) with open(temp, "xb") as f: @@ -797,7 +845,7 @@ def _commit( Raises `_Retry` if a concurrent `delete_dir` removed the directory on the way. """ try: - file.parent.mkdir(parents=True, exist_ok=True) + self._make_key_directories(file.parent) except (FileExistsError, NotADirectoryError) as e: if self._has_key_parent(file): raise KeyConflictError( diff --git a/packages/zarr-storage/tests/test_local.py b/packages/zarr-storage/tests/test_local.py index 6626b925a3..d266914e59 100644 --- a/packages/zarr-storage/tests/test_local.py +++ b/packages/zarr-storage/tests/test_local.py @@ -162,14 +162,36 @@ def test_create_makes_a_missing_root_and_keeps_an_existing_one( assert list(store.list()) == (["k"] if existing else []) -def test_put_never_recreates_the_directories_above_the_root(tmp_path: Path) -> None: - """A write recreates a removed root, but not the directories above it, which lie outside the - store (an unmounted volume must not be rebuilt elsewhere).""" - store = Store(LocalBackend.create(tmp_path / "volume" / "root")) - shutil.rmtree(tmp_path / "volume") - with pytest.raises(FileNotFoundError, match="recreates only the root"): +def test_put_recreates_a_removed_root_and_the_directories_above_it(tmp_path: Path) -> None: + """An enclosing backend's `delete_dir` can remove directories above a nested root too; a write + recreates them on the root's filesystem.""" + outer = Store(LocalBackend(tmp_path)) + inner = Store(LocalBackend.create(tmp_path / "g" / "inner")) + outer.delete_dir("g") + inner.put("k", b"x") + assert outer.exists("g/inner/k") + + +def _on_another_device(backend: LocalBackend) -> None: + """Make `backend` believe its root was made on another filesystem, as after the volume that + held it was unmounted.""" + backend._device += 1 + + +@pytest.mark.parametrize("removed", [True, False]) +def test_write_never_lands_on_another_filesystem(tmp_path: Path, removed: bool) -> None: + """With its volume unmounted, a root's path is gone (`removed`) or is an empty mount point on + the filesystem below; either way, writes refuse instead of writing there.""" + backend = LocalBackend.create(tmp_path / "volume" / "root") + store = Store(backend) + if removed: + shutil.rmtree(tmp_path / "volume") + _on_another_device(backend) + with pytest.raises(FileNotFoundError, match="another filesystem"): store.put("k", b"x") - assert not (tmp_path / "volume").exists() + with pytest.raises(FileNotFoundError, match="another filesystem"): + store.put_if_match("k", b"x", Generation(("x",))) + assert not (tmp_path / "volume").exists() if removed else not list(store.list()) def test_constructing_changes_nothing_on_disk(tmp_path: Path) -> None: From c90326a24f4b176383415006f6663e843a62cdff Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 21:45:11 +0100 Subject: [PATCH 27/31] revert(zarr-storage): restore LocalBackend's reviewed write path; list the unmounted-volume case as open Reverts 28c1c1993 and 203419628. Both changed how writes recreate a removed root and the directories above it, so that a write to an unmounted volume would not rebuild its path elsewhere; review found that each broke the retries the write path relies on under a concurrent `delete_dir` (deeper nested roots, EINVAL on macOS, the file-time probe). The write path is back to the reviewed version, and DESIGN.md lists the unmounted-volume behavior under "Open" with what a fix would need. Kept: `LocalBackend.create` resolves a relative root once and names both cases it can't tell apart. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/DESIGN.md | 15 ++-- .../src/zarr_storage/backends/_local.py | 82 +++---------------- packages/zarr-storage/tests/test_local.py | 32 -------- 3 files changed, 19 insertions(+), 110 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 0c015e1cf1..1756ccbd80 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -209,13 +209,7 @@ 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. A write recreates a root, -and directories above it, that have been removed (an enclosing backend's `delete_dir` can remove -them), but only on the filesystem the root was on when the backend was made: the backend records -the root's device, and a write that would create or land on another device (the root's volume -was unmounted, leaving its path missing or an empty mount point) raises `FileNotFoundError` -instead. Pickling carries the device, so on another machine a write that has to recreate the root -refuses. +`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); @@ -424,6 +418,13 @@ creates a directory reads as one. - 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; diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index 9b3e18e5b6..e9dfb4b1fb 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -95,7 +95,6 @@ class _State(TypedDict): root: str - device: int closed: bool @@ -522,7 +521,6 @@ def __init__(self, root: str | os.PathLike[str]) -> None: f"The root directory {str(self._root)!r} does not exist; " "`LocalBackend.create` makes it." ) - self._device = self._root.stat().st_dev self._probe_lock = threading.Lock() self._exact_times: bool | None = None self._closed = False @@ -553,11 +551,10 @@ def __repr__(self) -> str: return f"LocalBackend({str(self._root)!r})" def __getstate__(self) -> _State: - return {"root": str(self._root), "device": self._device, "closed": self._closed} + return {"root": str(self._root), "closed": self._closed} def __setstate__(self, state: _State) -> None: self._root = Path(state["root"]) - self._device = state["device"] self._probe_lock = threading.Lock() self._exact_times = None self._closed = state["closed"] @@ -710,81 +707,24 @@ def _require_exact_times(self) -> None: 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}" - for _ in range(_WRITE_ATTEMPTS): - try: - self._ensure_root() - staging.mkdir(exist_ok=True) - with open(probe, "xb") as f: - _set_mtime(f.fileno(), probe, _PROBE_STAMP) - return os.fstat(f.fileno()).st_mtime_ns == _PROBE_STAMP - except _Retry: - continue - except FileNotFoundError as e: - if e.errno != errno.ENOENT: - raise - continue # a concurrent delete_dir removed the staging directory - finally: - probe.unlink(missing_ok=True) - raise OSError("Gave up probing file times: a concurrent delete kept removing the root.") - - def _ensure_root(self) -> None: - """Make the root, and any directories above it, if they are gone, on the filesystem the - root was on when the backend was made, and never on another. - - An enclosing backend's `delete_dir` can remove the root and the directories above it; a - write recreates them. If the nearest directory that exists, or the root itself, is now on - another device (the volume holding the root was unmounted), it raises `FileNotFoundError` - instead of writing there. Raises `KeyConflictError` if a file is in the way, and `_Retry` if - a concurrent delete removed a directory it just made. - """ - missing: list[Path] = [] - path = self._root - while True: - try: - st = os.stat(path) - break - except (FileNotFoundError, NotADirectoryError): - missing.append(path) - path = path.parent - if not stat.S_ISDIR(st.st_mode): - where = "The root" if not missing else f"{str(path)!r}, above the root," - raise KeyConflictError( - f"{where} is now a file (a key of an enclosing store), so the root " - f"{str(self._root)!r} can't be a directory." - ) - if st.st_dev != self._device: - raise FileNotFoundError( - f"{str(path)!r} is not on the filesystem the root {str(self._root)!r} was on (was " - "its volume unmounted?); writes never create directories or files on another " - "filesystem." - ) - for directory in reversed(missing): - try: - directory.mkdir() - except FileExistsError: - pass # a concurrent write made it; a file in its place is found below - except FileNotFoundError as e: - raise _Retry from e - - def _make_key_directories(self, directory: Path) -> None: - """Make `directory` and the directories between the root and it, from the root down, so - nothing above the root is ever made here (that is `_ensure_root`'s job, with its check).""" - depth = len(directory.relative_to(self._root).parts) - for level in reversed([directory, *directory.parents][:depth]): - level.mkdir(exist_ok=True) + 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; see - `_ensure_root` for a root that is gone. + Raises `_Retry` if a concurrent delete removed the root or the staging directory. """ staging = self._root / _STAGING_NAME temp = staging / uuid.uuid4().hex - self._ensure_root() try: - staging.mkdir(exist_ok=True) + staging.mkdir(parents=True, exist_ok=True) with open(temp, "xb") as f: try: f.write(value) @@ -845,7 +785,7 @@ def _commit( Raises `_Retry` if a concurrent `delete_dir` removed the directory on the way. """ try: - self._make_key_directories(file.parent) + file.parent.mkdir(parents=True, exist_ok=True) except (FileExistsError, NotADirectoryError) as e: if self._has_key_parent(file): raise KeyConflictError( diff --git a/packages/zarr-storage/tests/test_local.py b/packages/zarr-storage/tests/test_local.py index d266914e59..53f2bbf5bd 100644 --- a/packages/zarr-storage/tests/test_local.py +++ b/packages/zarr-storage/tests/test_local.py @@ -162,38 +162,6 @@ def test_create_makes_a_missing_root_and_keeps_an_existing_one( assert list(store.list()) == (["k"] if existing else []) -def test_put_recreates_a_removed_root_and_the_directories_above_it(tmp_path: Path) -> None: - """An enclosing backend's `delete_dir` can remove directories above a nested root too; a write - recreates them on the root's filesystem.""" - outer = Store(LocalBackend(tmp_path)) - inner = Store(LocalBackend.create(tmp_path / "g" / "inner")) - outer.delete_dir("g") - inner.put("k", b"x") - assert outer.exists("g/inner/k") - - -def _on_another_device(backend: LocalBackend) -> None: - """Make `backend` believe its root was made on another filesystem, as after the volume that - held it was unmounted.""" - backend._device += 1 - - -@pytest.mark.parametrize("removed", [True, False]) -def test_write_never_lands_on_another_filesystem(tmp_path: Path, removed: bool) -> None: - """With its volume unmounted, a root's path is gone (`removed`) or is an empty mount point on - the filesystem below; either way, writes refuse instead of writing there.""" - backend = LocalBackend.create(tmp_path / "volume" / "root") - store = Store(backend) - if removed: - shutil.rmtree(tmp_path / "volume") - _on_another_device(backend) - with pytest.raises(FileNotFoundError, match="another filesystem"): - store.put("k", b"x") - with pytest.raises(FileNotFoundError, match="another filesystem"): - store.put_if_match("k", b"x", Generation(("x",))) - assert not (tmp_path / "volume").exists() if removed else not list(store.list()) - - def test_constructing_changes_nothing_on_disk(tmp_path: Path) -> None: before = sorted(p.name for p in tmp_path.iterdir()) LocalBackend(tmp_path) From 8dc17a1fe5a2683917b928c47c8d06d839ce30ca Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 23:19:43 +0100 Subject: [PATCH 28/31] feat(zarr-storage)!: compare stores by data location, and give each backend one owner From an audit of the store views' shared base: - `overlaps` compared backend objects, so two stores over different backend objects that see the same keys (two `LocalBackend`s over nested directories, the case behind #459's `from_array` data loss) reported no overlap. Every backend now names a `Location` (a space and a path, as a TensorStore kvstore is a driver spec plus a path): the local filesystem for `LocalBackend` and obstore's `LocalStore` alike, endpoint and bucket (or account and container, or URL) plus prefix for object stores, and an identity-only space for memory stores. `Store.location` appends the root, and `overlaps` compares locations. `Location` is exported and `location` joins the `Backend` protocol. - Constructors lose `root=`: the constructed store sees the backend from its root and owns it, so a second store over a backend is a view, not a second owner whose `close` closes the first's backend. - Every view is made by one private constructor that sets ownership once, instead of four places flipping `_owner` after construction. - `with_read_only(read_only=True)` becomes `as_read_only()`: the `False` form could only repeat the store or raise. - Write batches check keys (and duplicates) before refusing a read-only store, as single writes do, and a store that is read-only because its backend can't write says so. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/DESIGN.md | 29 +++- .../zarr-storage/src/zarr_storage/__init__.py | 2 + .../src/zarr_storage/_protocols.py | 7 + .../zarr-storage/src/zarr_storage/_store.py | 143 ++++++++++-------- .../zarr-storage/src/zarr_storage/_types.py | 29 +++- .../src/zarr_storage/backends/_common.py | 35 ++++- .../src/zarr_storage/backends/_local.py | 9 +- .../src/zarr_storage/backends/_memory.py | 15 +- .../src/zarr_storage/backends/_obstore.py | 45 +++++- .../src/zarr_storage/testing/_api.py | 13 +- .../src/zarr_storage/testing/_suite.py | 16 +- packages/zarr-storage/tests/test_local.py | 17 ++- packages/zarr-storage/tests/test_obstore.py | 40 ++++- packages/zarr-storage/tests/test_resources.py | 4 +- packages/zarr-storage/tests/test_store.py | 56 ++++++- 15 files changed, 356 insertions(+), 104 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index 1756ccbd80..fc48d25e5e 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -37,7 +37,8 @@ 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. Backends never see relative keys and never +`/`-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 @@ -156,14 +157,26 @@ it, and `put_if_match` raises `UnsupportedOperationError`. ## Views, lifecycle, identity -- `store / "a"`, `store.with_read_only(True)`, `store.with_context(ctx)`, `store.limited(n)` and +- `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. A view of a - read-only store is read-only; `with_read_only(False)` on one raises `ReadOnlyError`. -- The store the user constructed owns the backend. `close()` (`aclose()` on an `AsyncStore`) on it - closes the backend; on a derived view it does nothing. After the backend closes, every view raises `StoreClosedError`. -- No value equality: `==` is identity. `shares_backend(other)` and `overlaps(other)` answer the questions - callers actually ask. + 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, the endpoint and bucket (or account and container, or URL) and prefix for + object stores, and an identity-only space for a memory store or a store of an unknown kind. + 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. diff --git a/packages/zarr-storage/src/zarr_storage/__init__.py b/packages/zarr-storage/src/zarr_storage/__init__.py index d430790565..27c74d568e 100644 --- a/packages/zarr-storage/src/zarr_storage/__init__.py +++ b/packages/zarr-storage/src/zarr_storage/__init__.py @@ -53,6 +53,7 @@ Generation, Key, ListItem, + Location, Missing, ObjectMetadata, OffsetRequest, @@ -89,6 +90,7 @@ "ListItem", "Listable", "ListableAsync", + "Location", "Missing", "ObjectMetadata", "OffsetRequest", diff --git a/packages/zarr-storage/src/zarr_storage/_protocols.py b/packages/zarr-storage/src/zarr_storage/_protocols.py index 9ee4d03c56..0b5bb74c9b 100644 --- a/packages/zarr-storage/src/zarr_storage/_protocols.py +++ b/packages/zarr-storage/src/zarr_storage/_protocols.py @@ -42,6 +42,7 @@ FoundRanges, Generation, ListItem, + Location, Missing, ObjectMetadata, Rejected, @@ -90,6 +91,12 @@ def resource_key(self) -> str: """ ... + @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.""" diff --git a/packages/zarr-storage/src/zarr_storage/_store.py b/packages/zarr-storage/src/zarr_storage/_store.py index 1f32dafc2f..68165020e8 100644 --- a/packages/zarr-storage/src/zarr_storage/_store.py +++ b/packages/zarr-storage/src/zarr_storage/_store.py @@ -22,7 +22,7 @@ from zarr_storage._batch import run_many, run_many_async from zarr_storage._buffers import byte_view from zarr_storage._errors import BatchError, ReadOnlyError, StoreClosedError -from zarr_storage._keys import check_key, is_within, join, normalize_directory, relativize +from zarr_storage._keys import check_key, join, normalize_directory, relativize from zarr_storage._protocols import ( Backend, ClosableAsync, @@ -40,7 +40,7 @@ WritableManyAsync, ) from zarr_storage._resources import default_context -from zarr_storage._types import Missing +from zarr_storage._types import Location, Missing if TYPE_CHECKING: from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Sequence @@ -110,16 +110,38 @@ def __init__( self, backend: B_co, *, - root: str = "", - read_only: bool = False, - context: Context | None = None, + 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] = normalize_directory(root) + 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 = True + 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 @@ -148,10 +170,14 @@ 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: - view = type(self)(self._backend, root=root, read_only=read_only, context=context) - view._owner = False - return view + 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.""" @@ -161,15 +187,10 @@ def __truediv__(self, directory: str) -> Self: context=self._context, ) - def with_read_only(self, read_only: bool = True) -> Self: - """A view on the same backend and root that refuses writes, or accepts them. - - A read-only store can't produce a writable view: `with_read_only(False)` on one raises - `ReadOnlyError`. - """ - if self._read_only and not read_only: - raise ReadOnlyError(f"{self!r} is read-only; its views are read-only too.") - return self._view(root=self._root, read_only=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`.""" @@ -184,14 +205,14 @@ def limited(self, limit: int) -> Self: 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.""" + """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: same backend, nested roots.""" - return self.shares_backend(other) and ( - is_within(self._root, other._root) or is_within(other._root, self._root) - ) + """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 __repr__(self) -> str: flags = ", read_only=True" if self._read_only else "" @@ -210,9 +231,7 @@ def _restore( """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. - store = cls(cast("Any", backend), root=root, read_only=read_only, context=context) - store._owner = owner - return store + return cls._derived(backend, root=root, read_only=read_only, context=context, owner=owner) # ----------------------------------------------------------------- path handling @@ -231,16 +250,21 @@ def _directory(self, directory: str) -> str: 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) - if self._read_only: - raise ReadOnlyError(f"{self!r} is read-only.") + self._refuse_writes() return path def _writable_directory(self, directory: str) -> str: path = self._directory(directory) - if self._read_only: - raise ReadOnlyError(f"{self!r} is read-only.") + self._refuse_writes() return path def _read_request( @@ -261,16 +285,18 @@ def _into_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.""" + """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() - if self._read_only: - raise ReadOnlyError(f"{self!r} is read-only.") - paths = [self._writable_path(key) for key in keys] + 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( @@ -287,10 +313,10 @@ def _put_requests( class Store(_View[B_co]): """A backend seen from a root directory, under a context, through sync methods. - Construct a store from a backend; the store you construct owns the backend and closes it. - `store / "a"`, `with_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. + 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. @@ -299,17 +325,16 @@ class Store(_View[B_co]): 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. + 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` and `overlaps` to compare - stores. + 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. - root - The directory within the backend that this store's keys are relative to. read_only Refuse writes through this store. A backend that can't write makes every store over it read-only. @@ -320,22 +345,15 @@ class Store(_View[B_co]): __slots__ = () def __init__( - self, - backend: B_co, - *, - root: str = "", - read_only: bool = False, - context: Context | None = None, + self, backend: B_co, *, read_only: bool = False, context: Context | None = None ) -> None: - super().__init__(backend, root=root, read_only=read_only, context=context) + 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.""" - view = AsyncStore( + return AsyncStore[B_co]._derived( self._backend, root=self._root, read_only=self._read_only, context=self._context ) - view._owner = False - return view # ----------------------------------------------------------------- lifecycle @@ -613,15 +631,13 @@ class AsyncStore(_View[B_co]): 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 from a backend, or take `store.as_async()`; `as_sync()` goes back. + 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. - root - The directory within the backend that this store's keys are relative to. read_only Refuse writes through this store. A backend that can't write makes every store over it read-only. @@ -632,22 +648,15 @@ class AsyncStore(_View[B_co]): __slots__ = () def __init__( - self, - backend: B_co, - *, - root: str = "", - read_only: bool = False, - context: Context | None = None, + self, backend: B_co, *, read_only: bool = False, context: Context | None = None ) -> None: - super().__init__(backend, root=root, read_only=read_only, context=context) + 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.""" - view = Store( + return Store[B_co]._derived( self._backend, root=self._root, read_only=self._read_only, context=self._context ) - view._owner = False - return view # ----------------------------------------------------------------- lifecycle diff --git a/packages/zarr-storage/src/zarr_storage/_types.py b/packages/zarr-storage/src/zarr_storage/_types.py index 3c50860351..8b64518f15 100644 --- a/packages/zarr-storage/src/zarr_storage/_types.py +++ b/packages/zarr-storage/src/zarr_storage/_types.py @@ -3,7 +3,12 @@ from __future__ import annotations from dataclasses import dataclass -from typing import NewType +from typing import TYPE_CHECKING, NewType + +from zarr_storage._keys import is_within + +if TYPE_CHECKING: + from collections.abc import Hashable __all__ = [ "ByteRange", @@ -15,6 +20,7 @@ "Generation", "Key", "ListItem", + "Location", "Missing", "ObjectMetadata", "OffsetRequest", @@ -34,6 +40,27 @@ """ +@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 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: diff --git a/packages/zarr-storage/src/zarr_storage/backends/_common.py b/packages/zarr-storage/src/zarr_storage/backends/_common.py index 2cd5984317..4a4c81415b 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_common.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_common.py @@ -1,4 +1,4 @@ -"""Helpers shared by backends: preconditions, and listing a flat set of keys. +"""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 @@ -19,7 +19,38 @@ from zarr_storage._types import Generation, ListItem -__all__ = ["IfMatch", "always", "children", "if_absent", "strictly_within"] +__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: diff --git a/packages/zarr-storage/src/zarr_storage/backends/_local.py b/packages/zarr-storage/src/zarr_storage/backends/_local.py index e9dfb4b1fb..8d4a334408 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_local.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_local.py @@ -29,13 +29,14 @@ FoundRanges, Generation, Key, + Location, Missing, ObjectMetadata, Prefix, Unchanged, Written, ) -from zarr_storage.backends._common import IfMatch, always, if_absent +from zarr_storage.backends._common import LOCAL_FILESYSTEM, IfMatch, always, if_absent if TYPE_CHECKING: from collections.abc import Callable, Generator, Iterator, Sequence @@ -565,6 +566,12 @@ def __setstate__(self, state: _State) -> None: 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 diff --git a/packages/zarr-storage/src/zarr_storage/backends/_memory.py b/packages/zarr-storage/src/zarr_storage/backends/_memory.py index 69b5f0b231..c5f80de141 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_memory.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_memory.py @@ -15,12 +15,20 @@ Found, FoundRanges, Generation, + Location, Missing, ObjectMetadata, Unchanged, Written, ) -from zarr_storage.backends._common import IfMatch, always, children, if_absent, strictly_within +from zarr_storage.backends._common import ( + IfMatch, + Only, + always, + children, + if_absent, + strictly_within, +) if TYPE_CHECKING: from collections.abc import AsyncIterator, Callable, Iterator, Sequence @@ -83,6 +91,11 @@ def __setstate__(self, state: _State) -> None: 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 diff --git a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py index ff9f048d2e..ce3dfcc7e8 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py @@ -22,7 +22,7 @@ NotModifiedError, PreconditionError, ) -from obstore.store import HTTPStore, LocalStore +from obstore.store import AzureStore, GCSStore, HTTPStore, LocalStore, S3Store from zarr_storage._buffers import byte_view, copy_into from zarr_storage._byte_range import resolve @@ -34,6 +34,7 @@ FoundRanges, Generation, Key, + Location, Missing, ObjectMetadata, OffsetRequest, @@ -44,10 +45,10 @@ Unchanged, Written, ) -from zarr_storage.backends._common import IfMatch, always, if_absent +from zarr_storage.backends._common import LOCAL_FILESYSTEM, IfMatch, Only, always, if_absent if TYPE_CHECKING: - from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Sequence + from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Mapping, Sequence from obstore import GetOptions, GetResult, ListResult, ListStream, ObjectMeta, PutMode from obstore.store import ObjectStore @@ -68,6 +69,37 @@ """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: + 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): + return Location(("http", store.url), "") + if isinstance(store, (S3Store, GCSStore, AzureStore)): + config = cast("Mapping[str, object]", store.config) + space = _cloud_space(type(store).__name__, config) + prefix = store.prefix + if space is not None: + return Location(space, "" if prefix is None else str(prefix).strip("/")) + return Location(Only(store), "") + + +def _cloud_space(kind: str, config: Mapping[str, object]) -> tuple[str, ...] | None: + """What names a bucket (or container) in `config`; `None` if the config doesn't say.""" + keys = { + "S3Store": ("endpoint", "bucket"), + "GCSStore": ("bucket",), + "AzureStore": ("account_name", "container_name"), + }[kind] + if any(config.get(key) is None for key in keys if key != "endpoint"): + return None + return (kind, *(str(config.get(key, "")) for key in keys)) + + # ---------------------------------------------------------------------------- generations @@ -296,6 +328,13 @@ def __repr__(self) -> str: # --- 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 _location(self._store) + @property def closed(self) -> bool: return self._closed diff --git a/packages/zarr-storage/src/zarr_storage/testing/_api.py b/packages/zarr-storage/src/zarr_storage/testing/_api.py index e4f1a5cbd4..57a3f08b25 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/_api.py +++ b/packages/zarr-storage/src/zarr_storage/testing/_api.py @@ -102,7 +102,7 @@ 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 with_read_only(self, read_only: bool = True) -> Self: ... + def as_read_only(self) -> Self: ... def close(self) -> None: ... def __enter__(self) -> Self: ... def __exit__( @@ -134,8 +134,11 @@ async def _next(items: AsyncIterator[T]) -> T: def async_api(store: Store[FullBackend], runner: asyncio.Runner) -> AsyncAPI: - """An `AsyncAPI` over an `AsyncStore` that owns `store`'s backend, at its root.""" - return AsyncAPI(AsyncStore(store.backend, root=store.root, read_only=store.read_only), runner) + """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: @@ -242,8 +245,8 @@ def _iterate(self, items: AsyncIterator[T]) -> Iterator[T]: def __truediv__(self, directory: str) -> Self: return type(self)(self._store / directory, self._runner) - def with_read_only(self, read_only: bool = True) -> Self: - return type(self)(self._store.with_read_only(read_only), 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()) diff --git a/packages/zarr-storage/src/zarr_storage/testing/_suite.py b/packages/zarr-storage/src/zarr_storage/testing/_suite.py index 7a36a9a7ce..6007a4cb3f 100644 --- a/packages/zarr-storage/src/zarr_storage/testing/_suite.py +++ b/packages/zarr-storage/src/zarr_storage/testing/_suite.py @@ -967,7 +967,7 @@ def test_identity(self, store: StoreAPI, tmp_path_factory: pytest.TempPathFactor (base, lat, True, True), (lat, lat_bnds, True, False), (a, lat, True, False), - (a, a.with_read_only(), True, True), + (a, a.as_read_only(), True, True), (base, other, False, False), (a, other / "a", False, False), ] @@ -978,14 +978,10 @@ def test_identity(self, store: StoreAPI, tmp_path_factory: pytest.TempPathFactor def test_read_only_views(self, store: StoreAPI) -> None: store.put("k", VALUE) - reader = store.with_read_only() + 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") - assert not store.with_read_only(False).read_only - - def test_writable_view_of_read_only_store_raises(self, store: StoreAPI) -> None: - with pytest.raises(ReadOnlyError): - store.with_read_only().with_read_only(False) @pytest.mark.parametrize("write", WRITES, ids=WRITE_IDS) def test_write_through_read_only_view_raises( @@ -993,7 +989,7 @@ def test_write_through_read_only_view_raises( ) -> None: store.put("k", VALUE) with pytest.raises(ReadOnlyError): - write(store.with_read_only()) + write(store.as_read_only()) assert store.exists("k") # ------------------------------------------------------------------ lifecycle @@ -1001,7 +997,7 @@ def test_write_through_read_only_view_raises( def test_closing_a_derived_view_leaves_the_backend_open(self, store: StoreAPI) -> None: store.put("k", VALUE) (store / "a").close() - store.with_read_only().close() + store.as_read_only().close() assert not store.closed assert store.exists("k") @@ -1199,7 +1195,7 @@ class PickleSuite: @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).with_read_only(read_only)) + 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()) diff --git a/packages/zarr-storage/tests/test_local.py b/packages/zarr-storage/tests/test_local.py index 53f2bbf5bd..c35b85c6a6 100644 --- a/packages/zarr-storage/tests/test_local.py +++ b/packages/zarr-storage/tests/test_local.py @@ -10,6 +10,7 @@ from typing import TYPE_CHECKING import pytest +from obstore.store import LocalStore from zarr_storage import ( Found, @@ -24,7 +25,7 @@ UnsupportedOperationError, Written, ) -from zarr_storage.backends import LocalBackend, _local +from zarr_storage.backends import LocalBackend, ObjectStoreBackend, _local from zarr_storage.backends._local import RESERVED_SUFFIX, _directory_lock, segment_problem from zarr_storage.testing import ( ConditionalDeleteSuite, @@ -528,3 +529,17 @@ def test_if_match_on_a_filesystem_that_rounds_times_raises( 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/test_obstore.py b/packages/zarr-storage/tests/test_obstore.py index 82edcd6f10..f13ea5bb21 100644 --- a/packages/zarr-storage/tests/test_obstore.py +++ b/packages/zarr-storage/tests/test_obstore.py @@ -6,7 +6,7 @@ import obstore import pytest from obstore.exceptions import GenericError -from obstore.store import LocalStore, MemoryStore +from obstore.store import HTTPStore, LocalStore, MemoryStore, S3Store from zarr_storage import Found, Generation, ObjectMetadata, RangeRequest, Store, Unchanged from zarr_storage.backends import ObjectStoreBackend @@ -214,3 +214,41 @@ def test_get_if_changed_of_a_store_without_etags_or_versions_reads_the_value( 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 _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), + ( + Store(ObjectStoreBackend(HTTPStore.from_url("https://example.com/d"))), + Store(ObjectStoreBackend(HTTPStore.from_url("https://example.com/d"))), + True, + ), + ], +) +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 + + +def test_object_store_location_has_no_credentials() -> None: + store = S3Store("b", region="us-east-1", access_key_id="AKIA", secret_access_key="secret") + assert "secret" not in repr(Store(ObjectStoreBackend(store)).location) diff --git a/packages/zarr-storage/tests/test_resources.py b/packages/zarr-storage/tests/test_resources.py index ecd11e8c74..fbe4dee228 100644 --- a/packages/zarr-storage/tests/test_resources.py +++ b/packages/zarr-storage/tests/test_resources.py @@ -315,8 +315,8 @@ def test_context_of_a_bad_resource_raises(make: Callable[[], Context]) -> None: 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(), root="r", context=context) - for view in (store / "a", store.with_read_only(), store.as_async(), store.as_async().as_sync()): + 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 diff --git a/packages/zarr-storage/tests/test_store.py b/packages/zarr-storage/tests/test_store.py index 1a988b75f0..33cd57f544 100644 --- a/packages/zarr-storage/tests/test_store.py +++ b/packages/zarr-storage/tests/test_store.py @@ -15,10 +15,13 @@ Found, FoundRanges, Generation, + InvalidKeyError, + Location, Missing, ObjectMetadata, OffsetRequest, RangeRequest, + ReadOnlyError, Store, SuffixRequest, Unchanged, @@ -43,6 +46,10 @@ def __init__(self, values: dict[str, bytes]) -> None: def resource_key(self) -> str: return "test" + @property + def location(self) -> Location: + return Location(("test", id(self)), "") + @property def closed(self) -> bool: return False @@ -267,7 +274,8 @@ def test_store_is_not_value_equal() -> None: 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() - store = Store(backend, root=root, read_only=read_only) + 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): @@ -278,8 +286,9 @@ def test_views_across_sync_and_async(root: str, read_only: bool) -> None: assert isinstance(sync_view, Store) asyncio.run(async_view.aclose()) sync_view.close() - assert not backend.closed store.close() + assert not backend.closed + owner.close() assert backend.closed @@ -353,3 +362,46 @@ def test_pickled_derived_views_do_not_own_the_backend() -> None: 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") From ba5e2d09738e27ebab959e402355bb0995a450d6 Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 23:24:43 +0100 Subject: [PATCH 29/31] fix(zarr-storage): normalize object-store locations and keep credentials out of them From review of 8dc17a1fe: - An obstore `LocalStore` with a relative prefix resolved it against the working directory each time `location` was read; it is now read once, when the backend is made, as the store resolves its own. - An HTTP store's location held the whole URL as its space, so nested URLs never overlapped; the space is now the scheme and host, and the URL's path is the path. - User names, passwords and query strings (a presigned URL's signature) are dropped from URLs and S3 endpoints, and an endpoint's trailing `/` no longer makes a different space. - `Location` refuses a path that isn't a normalized directory. - `copy.copy` of a store returns the store, instead of a second owner of the same backend object. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/DESIGN.md | 7 ++- .../zarr-storage/src/zarr_storage/_store.py | 5 ++ .../zarr-storage/src/zarr_storage/_types.py | 6 +- .../src/zarr_storage/backends/_obstore.py | 56 +++++++++++++------ packages/zarr-storage/tests/test_obstore.py | 47 +++++++++++++--- packages/zarr-storage/tests/test_store.py | 15 +++++ 6 files changed, 108 insertions(+), 28 deletions(-) diff --git a/packages/zarr-storage/DESIGN.md b/packages/zarr-storage/DESIGN.md index fc48d25e5e..817f932777 100644 --- a/packages/zarr-storage/DESIGN.md +++ b/packages/zarr-storage/DESIGN.md @@ -171,8 +171,11 @@ it, and `put_if_match` raises `UnsupportedOperationError`. 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, the endpoint and bucket (or account and container, or URL) and prefix for - object stores, and an identity-only space for a memory store or a store of an unknown kind. + `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 diff --git a/packages/zarr-storage/src/zarr_storage/_store.py b/packages/zarr-storage/src/zarr_storage/_store.py index 68165020e8..9bec0dbb73 100644 --- a/packages/zarr-storage/src/zarr_storage/_store.py +++ b/packages/zarr-storage/src/zarr_storage/_store.py @@ -214,6 +214,11 @@ def overlaps(self, other: Store[Backend] | AsyncStore[Backend]) -> bool: 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})" diff --git a/packages/zarr-storage/src/zarr_storage/_types.py b/packages/zarr-storage/src/zarr_storage/_types.py index 8b64518f15..d04ee9f82a 100644 --- a/packages/zarr-storage/src/zarr_storage/_types.py +++ b/packages/zarr-storage/src/zarr_storage/_types.py @@ -5,7 +5,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, NewType -from zarr_storage._keys import is_within +from zarr_storage._keys import check_key, is_within if TYPE_CHECKING: from collections.abc import Hashable @@ -54,6 +54,10 @@ class 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 ( diff --git a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py index ce3dfcc7e8..3d4ad58338 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py @@ -14,6 +14,7 @@ import time from pathlib import Path from typing import TYPE_CHECKING, TypeVar, cast +from urllib.parse import urlsplit import obstore from obstore.exceptions import ( @@ -73,31 +74,51 @@ 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): - return Location(("http", store.url), "") - if isinstance(store, (S3Store, GCSStore, AzureStore)): - config = cast("Mapping[str, object]", store.config) - space = _cloud_space(type(store).__name__, config) - prefix = store.prefix - if space is not None: - return Location(space, "" if prefix is None else str(prefix).strip("/")) + 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(kind: str, config: Mapping[str, object]) -> tuple[str, ...] | None: - """What names a bucket (or container) in `config`; `None` if the config doesn't say.""" - keys = { - "S3Store": ("endpoint", "bucket"), - "GCSStore": ("bucket",), - "AzureStore": ("account_name", "container_name"), - }[kind] - if any(config.get(key) is None for key in keys if key != "endpoint"): +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 (kind, *(str(config.get(key, "")) for key in keys)) + return ("azure", str(account), str(container)) + + +def _url_parts(url: str) -> tuple[str, str, str]: + """`url`'s scheme, host (and port), and path, without the user name, password, query or + fragment, which may hold credentials (a presigned URL's signature) and don't name data.""" + parts = urlsplit(url) + host = "" if parts.hostname is None else parts.hostname + if parts.port is not None: + host = f"{host}:{parts.port}" + return parts.scheme.lower(), host, parts.path.strip("/") # ---------------------------------------------------------------------------- generations @@ -310,6 +331,7 @@ def __init__( 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 @property @@ -333,7 +355,7 @@ 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 _location(self._store) + return self._location @property def closed(self) -> bool: diff --git a/packages/zarr-storage/tests/test_obstore.py b/packages/zarr-storage/tests/test_obstore.py index f13ea5bb21..ce38bae656 100644 --- a/packages/zarr-storage/tests/test_obstore.py +++ b/packages/zarr-storage/tests/test_obstore.py @@ -9,7 +9,7 @@ from obstore.store import HTTPStore, LocalStore, MemoryStore, S3Store from zarr_storage import Found, Generation, ObjectMetadata, RangeRequest, Store, Unchanged -from zarr_storage.backends import ObjectStoreBackend +from zarr_storage.backends import LocalBackend, ObjectStoreBackend from zarr_storage.backends import _obstore as obstore_backend from zarr_storage.backends._obstore import _empty_read_or_raise, _generation from zarr_storage.testing import ( @@ -26,6 +26,8 @@ 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"] @@ -220,6 +222,14 @@ 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)) @@ -234,11 +244,11 @@ def _minio(bucket: str) -> Store[ObjectStoreBackend]: (_s3("b"), _s3("c"), False), (_minio("b"), _s3("b"), False), (Store(ObjectStoreBackend(MemoryStore())), Store(ObjectStoreBackend(MemoryStore())), False), - ( - Store(ObjectStoreBackend(HTTPStore.from_url("https://example.com/d"))), - Store(ObjectStoreBackend(HTTPStore.from_url("https://example.com/d"))), - True, - ), + (_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), ], ) def test_object_store_locations( @@ -249,6 +259,27 @@ def test_object_store_locations( assert left.overlaps(right) is overlaps -def test_object_store_location_has_no_credentials() -> None: - store = S3Store("b", region="us-east-1", access_key_id="AKIA", secret_access_key="secret") +@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"))) diff --git a/packages/zarr-storage/tests/test_store.py b/packages/zarr-storage/tests/test_store.py index 33cd57f544..5ae611b275 100644 --- a/packages/zarr-storage/tests/test_store.py +++ b/packages/zarr-storage/tests/test_store.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import copy import pickle from typing import TYPE_CHECKING @@ -405,3 +406,17 @@ 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" From 8af4f06eebe814b7363c7781796288ba8dff1fef Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 23:27:52 +0100 Subject: [PATCH 30/31] fix(zarr-storage): recompute an obstore location on unpickling, and normalize URL paths From review of ba5e2d097: - The location was pickled with the backend, but an unpickled `LocalStore` resolves a relative prefix again against the receiving process's working directory, so the store wrote to one place and reported another. The location is now left out of the pickle and recomputed. - URL paths (an HTTP store's, an S3 endpoint's) are decoded and normalized (empty and `.` segments dropped, `..` applied), so `https://h/a//b` builds instead of raising and percent-encoded names compare as keys. Default ports are dropped, IPv6 hosts keep their brackets, and an endpoint whose port isn't a number no longer makes construction raise. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- .../src/zarr_storage/backends/_obstore.py | 48 ++++++++++++++++--- packages/zarr-storage/tests/test_obstore.py | 26 ++++++++++ 2 files changed, 68 insertions(+), 6 deletions(-) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py index 3d4ad58338..ff94acc658 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py @@ -14,7 +14,7 @@ import time from pathlib import Path from typing import TYPE_CHECKING, TypeVar, cast -from urllib.parse import urlsplit +from urllib.parse import unquote, urlsplit import obstore from obstore.exceptions import ( @@ -111,14 +111,41 @@ def _cloud_space(store: ObjectStore) -> tuple[str, ...] | 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 (and port), and path, without the user name, password, query or - fragment, which may hold credentials (a presigned URL's signature) and don't name data.""" + """`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 parts.port is not None: - host = f"{host}:{parts.port}" - return parts.scheme.lower(), host, parts.path.strip("/") + 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.""" + segments: list[str] = [] + for segment in unquote(path).split("/"): + if segment in ("", "."): + continue + if segment == "..": + if segments: + segments.pop() + continue + segments.append(segment) + return "/".join(segments) # ---------------------------------------------------------------------------- generations @@ -334,6 +361,15 @@ def __init__( 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.""" diff --git a/packages/zarr-storage/tests/test_obstore.py b/packages/zarr-storage/tests/test_obstore.py index ce38bae656..0e96b470a1 100644 --- a/packages/zarr-storage/tests/test_obstore.py +++ b/packages/zarr-storage/tests/test_obstore.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import pickle from typing import TYPE_CHECKING import obstore @@ -249,6 +250,10 @@ def _minio(bucket: str) -> Store[ObjectStoreBackend]: (_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), ], ) def test_object_store_locations( @@ -283,3 +288,24 @@ def test_local_store_location_is_fixed_when_the_backend_is_made( 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) From fce03f91e50d72a9d28fe31c75cc709e48c4659b Mon Sep 17 00:00:00 2001 From: Davis Vann Bennett Date: Tue, 1 Dec 2026 23:30:12 +0100 Subject: [PATCH 31/31] fix(zarr-storage): keep a URL path segment that decodes to NUL encoded Decoding `https://h/a%00b` gave a location path with a NUL, which `Location` refuses, so building a backend over a URL obstore accepts raised. Such a segment now stays encoded; no key can hold a NUL, so it overlaps no decoded name. Assisted-by: ClaudeCode:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 --- packages/zarr-storage/src/zarr_storage/backends/_obstore.py | 5 +++-- packages/zarr-storage/tests/test_obstore.py | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py index ff94acc658..f0732f7cfe 100644 --- a/packages/zarr-storage/src/zarr_storage/backends/_obstore.py +++ b/packages/zarr-storage/src/zarr_storage/backends/_obstore.py @@ -135,9 +135,10 @@ def _url_parts(url: str) -> tuple[str, str, str]: def _url_path(path: str) -> str: """A URL path as a normalized directory: decoded, without empty or `.` segments, and with - `..` applied.""" + `..` applied. A segment that decodes to a NUL, which no key holds, stays encoded.""" segments: list[str] = [] - for segment in unquote(path).split("/"): + 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 == "..": diff --git a/packages/zarr-storage/tests/test_obstore.py b/packages/zarr-storage/tests/test_obstore.py index 0e96b470a1..60faa4d24d 100644 --- a/packages/zarr-storage/tests/test_obstore.py +++ b/packages/zarr-storage/tests/test_obstore.py @@ -254,6 +254,7 @@ def _minio(bucket: str) -> Store[ObjectStoreBackend]: (_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(